调用AWS get_credentials_for_identity时提示Identity '[]' not found问题求助
问题分析与解决方案
核心错误原因
你遇到的Identity '[]' not found错误,本质是直接硬编码了不存在的Identity ID,或是混淆了Identity Pool ID与用户Identity ID的区别:
- Identity Pool ID是你的身份池标识(格式
区域:UUID),而用户的Identity ID是AWS为每个用户(认证/未认证)生成的唯一标识,不能手动指定,必须通过GetId接口获取。
具体修复步骤
1. 修正流程:先调用GetId获取Identity ID
不管是未认证用户还是认证用户,都需要先调用GetId生成用户的Identity ID,再用这个ID调用GetCredentialsForIdentity:
- 未认证用户场景:不需要传入
logins参数,直接调用GetId并指定你的Identity Pool ID。 - 认证用户场景:传入
logins参数(Cognito User Pool的令牌)和Identity Pool ID,获取对应认证用户的Identity ID。
2. 修复代码示例
以下是修正后的Rust代码,分两种场景:
场景1:未认证用户获取凭证
use aws_sdk_cognitoidentity::{Client, types::IdentityPoolId}; use aws_credential_types::Credentials; // 初始化无凭证的配置(用于调用Cognito Identity的公共接口) let unauth_config = aws_config::defaults(aws_config::BehaviorVersion::latest()) .region("eu-central-1") .no_credentials() .load() .await; let identity_client = Client::new(&unauth_config); // 第一步:获取未认证用户的Identity ID let get_id_res = identity_client .get_id() .identity_pool_id("eu-central-1:你的Identity Pool ID") .send() .await; let identity_id = match get_id_res { Ok(res) => res.identity_id.unwrap(), Err(err) => { eprintln!("获取Identity ID失败: {}", err); return; } }; // 第二步:通过Identity ID获取STS凭证 let cred_res = identity_client .get_credentials_for_identity() .identity_id(&identity_id) .send() .await; match cred_res { Ok(credentials) => { if let Some(cred) = credentials.credentials { // 直接用凭证创建S3客户端,无需修改环境变量 let s3_config = aws_config::defaults(aws_config::BehaviorVersion::latest()) .region("eu-central-1") .credentials_provider(Credentials::new( cred.access_key_id.unwrap(), cred.secret_key.unwrap(), cred.session_token, cred.expiration, "cognito-identity", )) .load() .await; let s3_client = aws_sdk_s3::Client::new(&s3_config); json_bytes = get_object(s3_client, "etisreal-cognito-bucket", req_obj).await.unwrap(); } else { eprintln!("未获取到凭证"); } }, Err(err) => { eprintln!("获取凭证失败: {}", err); } }
场景2:认证用户(Cognito User Pool用户)获取凭证
如果你的logins参数是有效的User Pool令牌,修改GetId调用时传入logins:
// 获取认证用户的Identity ID let get_id_res = identity_client .get_id() .identity_pool_id("eu-central-1:你的Identity Pool ID") .logins("cognito-idp.eu-central-1.amazonaws.com/eu-central-1_vexpZDVTF", "你的有效JWT令牌") .send() .await;
3. 其他关键修复点
- 不要修改环境变量:
aws_config::load_from_env()会在程序启动时读取环境变量,后续修改不会生效,直接用获取到的凭证创建客户端更可靠。 - 验证Identity Pool配置:确保你的Identity Pool已经启用了未认证访问(如果是未认证场景),并且对应的IAM角色有访问目标S3桶的权限。
- 检查JWT令牌有效性:如果是认证场景,确保传入的JWT令牌未过期、签名正确,且属于对应的User Pool。
4. 错误排查建议
- 打印完整错误信息:不要只匹配特定错误类型,直接打印
err.to_string(),可获取更详细的错误细节。 - 用AWS CLI测试:先通过CLI调用
aws cognito-identity get-id --identity-pool-id 你的池ID(未认证)或加上--logins '{"cognito-idp...": "令牌"}'(认证),验证是否能获取到Identity ID,排除代码外的配置问题。
内容的提问来源于stack exchange,提问作者ETisREAL
相关产品推荐
相关产品推荐

