Rust AWS身份认证库aws-sdk-cognitoidentity的使用:实现安全用户身份管理与AWS服务集成
根据要求,我将直接输出内容中提供的示例,然后给出一个完整的示例代码。
以下是内容中提供的示例代码:
use aws_sdk_cognitoidentity::{Client, Error};
use aws_sdk_cognitoidentity::model::{IdentityPool, Credentials};
#[tokio::main]
async fn main() -> Result<(), Error> {
// 加载配置
let config = aws_config::load_from_env().await;
// 创建客户端
let client = Client::new(&config);
// 创建身份池
let pool_name = "my-identity-pool";
let create_pool_output = client
.create_identity_pool()
.identity_pool_name(pool_name)
.allow_unauthenticated_identities(true)
.send()
.await?;
println!("Created identity pool: {:?}", create_pool_output.identity_pool_id());
// 获取ID
let identity_id = create_pool_output.identity_pool_id().unwrap();
// 获取凭证
let credentials_output = client
.get_credentials_for_identity()
.identity_id(identity_id.to_string())
.send()
.await?;
if let Some(creds) = credentials_output.credentials() {
println!("Access Key: {}", creds.access_key_id().unwrap());
println!("Secret Key: {}", creds.secret_key().unwrap());
println!("Session Token: {}", creds.session_token().unwrap());
println!("Expiration: {:?}", creds.expiration());
}
Ok(())
}
现在,我将提供一个更完整的示例,展示如何集成第三方登录提供商和设置IAM角色:
use aws_sdk_cognitoidentity::{Client, Error};
use aws_sdk_cognitoidentity::model::{IdentityPool, Credentials, RoleMapping, RulesConfigurationType, MappingRule};
#[tokio::main]
async fn main() -> Result<(), Error> {
// 加载AWS配置
let config = aws_config::load_from_env().await;
// 创建Cognito Identity客户端
let client = Client::new(&config);
// 1. 创建身份池并配置Google登录提供商
let pool_name = "enhanced-identity-pool";
let google_client_id = "your-google-client-id"; // 替换为实际的Google客户端ID
let create_pool_output = client
.create_identity_pool()
.identity_pool_name(pool_name)
.allow_unauthenticated_identities(false) // 禁用未认证访问
.supported_login_providers("accounts.google.com".to_string(), google_client_id.to_string())
.send()
.await?;
println!("创建的身份池ID: {:?}", create_pool_output.identity_pool_id());
// 2. 设置IAM角色映射
let identity_id = create_pool_output.identity_pool_id().unwrap();
let authenticated_role_arn = "arn:aws:iam::123456789012:role/Cognito_Authenticated_Role"; // 替换为实际的角色ARN
let role_mapping = RoleMapping::builder()
.type_("Rules")
.rules_configuration(
RulesConfigurationType::builder()
.rules(
MappingRule::builder()
.claim("iss")
.match_type("Equals")
.value("accounts.google.com")
.role_arn(authenticated_role_arn)
.build()
)
.build()
)
.build();
client
.set_identity_pool_roles()
.identity_pool_id(identity_id.to_string())
.roles("authenticated".to_string(), authenticated_role_arn.to_string())
.role_mappings("accounts.google.com".to_string(), role_mapping)
.send()
.await?;
println!("成功设置身份池角色映射");
// 3. 获取Google登录后的凭证
let google_token = "google-id-token"; // 替换为实际的Google ID令牌
let credentials_output = client
.get_credentials_for_identity()
.identity_id(identity_id.to_string())
.logins("accounts.google.com".to_string(), google_token.to_string())
.send()
.await?;
if let Some(creds) = credentials_output.credentials() {
println!("获取到的凭证:");
println!("Access Key: {}", creds.access_key_id().unwrap());
println!("Secret Key: {}", creds.secret_key().unwrap());
println!("Session Token: {}", creds.session_token().unwrap());
println!("过期时间: {:?}", creds.expiration());
}
Ok(())
}
代码说明:
-
这个完整示例展示了:
- 创建身份池并配置Google登录提供商
- 设置IAM角色映射,为认证用户分配特定角色
- 使用Google登录令牌获取临时AWS凭证
-
主要功能点:
- 通过
supported_login_providers
添加Google登录支持 - 使用
set_identity_pool_roles
配置IAM角色映射 - 通过
get_credentials_for_identity
获取认证后的凭证
- 通过
-
使用前需要:
- 替换示例中的Google客户端ID和角色ARN
- 确保已正确配置AWS凭证
- 在Google开发者控制台设置OAuth客户端
注意事项:
- 实际使用时需要替换示例中的占位值为真实值
- 确保IAM角色具有适当的权限
- 生产环境应考虑错误处理和令牌刷新机制
1 回复
Rust AWS身份认证库aws-sdk-cognitoidentity的使用:实现安全用户身份管理与AWS服务集成
概述
aws-sdk-cognitoidentity
是AWS官方提供的Rust SDK中的Cognito身份认证服务库,用于实现安全的用户身份管理并与AWS服务集成。Cognito Identity提供了用户身份池功能,允许开发者创建唯一身份并授权用户访问AWS资源。
主要功能
- 创建和管理身份池
- 获取临时AWS凭证
- 实现联合身份认证
- 与社交登录提供商集成
- 管理身份池角色
使用方法
添加依赖
首先在Cargo.toml中添加依赖:
[dependencies]
aws-config = "0.55"
aws-sdk-cognitoidentity = "0.28"
tokio = { version = "1", features = ["full"] }
基本使用示例
1. 初始化客户端
use aws_sdk_cognitoidentity::{Client, Error};
async fn create_client() -> Result<Client, Error> {
let config = aws_config::load_from_env().await;
let client = Client::new(&config);
Ok(client)
}
2. 创建身份池
use aws_sdk_cognitoidentity::model::IdentityPool;
async fn create_identity_pool(client: &Client, pool_name: &str) -> Result<String, Error> {
let response = client
.create_identity_pool()
.identity_pool_name(pool_name)
.allow_unauthenticated_identities(true)
.send()
.await?;
Ok(response.identity_pool_id().unwrap().to_string())
}
3. 获取身份ID
async fn get_id(client: &Client, pool_id: &str, provider_name: &str, token: &str) -> Result<String, Error> {
let response = client
.get_id()
.identity_pool_id(pool_id)
.logins(provider_name, token)
.send()
.await?;
Ok(response.identity_id().unwrap().to_string())
}
4. 获取临时凭证
use aws_sdk_cognitoidentity::model::Credentials;
async fn get_credentials(
client: &Client,
identity_id: &str,
provider_name: &str,
token: &str,
) -> Result<Credentials, Error> {
let response = client
.get_credentials_for_identity()
.identity_id(identity_id)
.logins(provider_name, token)
.send
.await?;
Ok(response.credentials().unwrap().clone())
}
完整示例
以下是一个完整的示例,展示如何创建身份池并获取临时凭证:
use aws_sdk_cognitoidentity::{Client, Error};
use aws_sdk_cognitoidentity::model::IdentityPool;
#[tokio::main]
async fn main() -> Result<(), Error> {
// 初始化客户端
let config = aws_config::load_from_env().await;
let client = Client::new(&config);
// 创建身份池
let pool_name = "MyRustIdentityPool";
let pool_id = create_identity_pool(&client, pool_name).await?;
println!("Created identity pool with ID: {}", pool_id);
// 模拟社交登录提供商的token
let provider_name = "graph.facebook.com";
let token = "sample-facebook-token";
// 获取身份ID
let identity_id = get_id(&client, &pool_id, provider_name, token).await?;
println!("Got identity ID: {}", identity_id);
// 获取临时凭证
let credentials = get_credentials(&client, &identity_id, provider_name, token).await?;
println!("Temporary credentials:");
println!("Access Key ID: {}", credentials.access_key_id().unwrap());
println!("Secret Key: {}", credentials.secret_key().unwrap());
println!("Session Token: {}", credentials.session_token().unwrap());
println!("Expiration: {}", credentials.expiration().unwrap());
Ok(())
}
async fn create_identity_pool(client: &Client, pool_name: &str) -> Result<String, Error> {
let response = client
.create_identity_pool()
.identity_pool_name(pool_name)
.allow_unauthenticated_identities(true)
.send()
.await?;
Ok(response.identity_pool_id().unwrap().to_string())
}
async fn get_id(client: &Client, pool_id: &str, provider_name: &str, token: &str) -> Result<String, Error> {
let response = client
.get_id()
.identity_pool_id(pool_id)
.logins(provider_name, token)
.send()
.await?;
Ok(response.identity_id().unwrap().to_string())
}
async fn get_credentials(
client: &Client,
identity_id: &str,
provider_name: &str,
token: &str,
) -> Result<aws_sdk_cognitoidentity::model::Credentials, Error> {
let response = client
.get_credentials_for_identity()
.identity_id(identity_id)
.logins(provider_name, token)
.send()
.await?;
Ok(response.credentials().unwrap().clone())
}
最佳实践
- 安全存储凭证:临时凭证应该安全存储并定期刷新
- 最小权限原则:为身份池角色分配最小必要权限
- 错误处理:妥善处理各种认证失败的情况
- 日志记录:记录认证过程中的重要事件
- 使用HTTPS:确保所有通信都通过HTTPS进行
常见问题
- 权限不足:确保IAM角色有正确的权限策略
- Token过期:实现Token刷新逻辑
- 区域设置:确保客户端配置了正确的AWS区域
- 身份池未启用:检查身份池是否已正确配置并启用
通过aws-sdk-cognitoidentity
库,Rust开发者可以轻松实现安全的用户身份管理,并与AWS服务无缝集成。