我正在使用 AWS Congito 用户池通过 Cognito 身份池进行账户管理,该身份池将此用户池作为身份提供者。我使用它来控制通过 API 网关对 API 的访问,该网关将请求发送到 Lambda。我的 Lambda 是使用 Micronaut 用 Java 8 实现的。所有这些都运行良好。
在 Lambda 中,我从 Principal
中获取名称在 HttpRequest
:
protected String resolveUser( HttpRequest request ){
String ret = null;
Optional<Principal> principal = request.getUserPrincipal();
if( principal.isPresent() ){
ret = principal.get().getName();
}
if( ret == null || ret.length() == 0 ){
ret = "unknown";
}
return ret;
}
Cognito identityId 的字符串名称中返回的内容。像这样的东西:us-east-1:xxxxe650-53f4-4cba-b553-5dff42bexxxx
我想记录实际的用户登录信息,或者至少有一些方法可以在需要时将 identityId 转换为登录信息。
LookupDeveloperIdentity API 调用似乎是解决此问题的正确方法,但我无法使其正常工作。
尝试使用 Java 和 AWS Java SDK 2 执行此操作:
protected String loadUsername( String user ){
String ret = "unknown:"+user;
CognitoIdentityClient cognito = CognitoIdentityClient.create();
LookupDeveloperIdentityRequest request = LookupDeveloperIdentityRequest.builder()
.identityPoolId( identityPoolId )
.identityId( user )
.build();
LookupDeveloperIdentityResponse response = cognito.lookupDeveloperIdentity( request );
List<String> identifiers = response.developerUserIdentifierList();
if( identifiers != null && identifiers.size() > 0 ){
ret = identifiers.get( 0 );
}
return ret;
}
抛出异常software.amazon.awssdk.services.cognitoidentity.model.NotAuthorizedException: You do not have access to this identity (Service: CognitoIdentity, Status Code: 400, Request ID: 64e36646-612b-4985-91d1-82aca770XXXX)
尝试通过 CLI 执行此操作会产生类似的结果:
aws cognito-identity lookup-developer-identity --identity-id us-east-1:xxxxe650-53f4-4cba-b553-5dff42bexxxx --identity-pool-id us-east-1:xxxx0aa1-89f9-4418-be04-7e83c838xxxx --max-results=10
An error occurred (NotAuthorizedException) when calling the LookupDeveloperIdentity operation: You do not have access to this identity
我已经确保现有的 IAM 策略应该能够处理这个问题,当我尝试使用没有此策略的角色时,我收到了不同的错误
{
"Effect": "Allow",
"Action": [
"cognito-identity:LookupDeveloperIdentity"
],
"Resource": [
"arn:aws:cognito-identity:us-east-1:##########:identitypool/us-east-1:xxxx0aa1-89f9-4418-be04-7e83c838xxxx"
]
}
所以问题归结为:最佳答案
替代方法
为了检索用户的用户池用户 ID,您可以在 lambda 中检索:
authProvider = event.requestContext.identity.cognitoAuthenticationProvider;
这将返回一个字符串,其中包含用户的用户池用户 ID,它看起来像:
cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxxxxxx,cognito-idp.us-east-1.amazonaws.com/us-east-1_aaaaaaaaa:CognitoSignIn:qqqqqqqq-1111-2222-3333-rrrrrrrrrrrr
其中 us-east-1_aaaaaaaaa 是用户池 ID,qqqqqqqq-1111-2222-3333-rrrrrrrrrrrr 是用户池用户 ID。然后,您可以拆分字符串并提取用户 ID。
请注意,根据您使用的身份验证提供程序,这些信息会有所不同。
然后,如果您需要用户名而不是用户 ID,您可以通过获取该特定用户 ID 的适当详细信息直接从用户池中提取它。
引用
https://serverless-stack.com/chapters/mapping-cognito-identity-id-and-user-pool-id.html
关于amazon-web-services - 从 Cognito 身份池 identityId 获取 Cognito 用户池用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567546/