如何为Cognito承担跨帐户角色?

时间:2020-05-11 21:15:10

标签: amazon-web-services amazon-cognito amazon-iam

  • 我在AWS账户acc-1上有一个Cognito用户池,在acc-2上运行了一个Java代码,该代码使用“ adminInitiateAuth”进行身份验证,由于某些原因,我无法使用clientInitiateAuth。
  • 我已经在acc-1上创建了一个跨帐户角色,以我在acc-2上的Java代码为假设

问题::当我向Cognito发送身份验证请求时,如何承担角色?可以使用withRoleArn()吗?

我碰到了this页,该页说明了如何“使用API​​ Gateway控制台配置REST API的跨账户Amazon Cognito授权者”。但这不是我想要做的。

我的代码:

    protected AdminInitiateAuthRequest createInitialRequest(String username, String password) {
        Map<String, String> authParams = new HashMap<>();
        authParams.put("USERNAME", username);
        authParams.put("PASSWORD", password);

        return new AdminInitiateAuthRequest()
                .withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH)
                .withAuthParameters(authParams)
                .withClientId(whoAmIService.getCognitoClientId())
                .withUserPoolId(whoAmIService.getCognitoPoolId());
    }

protected boolean isAuthenticatedByCognito(String username, String password) {
        AWSCognitoIdentityProvider awsCognitoIDPClient = createCognitoIDPClient();
        AdminInitiateAuthRequest authRequest = createInitialRequest(username, password);

        try {
            AdminInitiateAuthResult authResponse = awsCognitoIDPClient.adminInitiateAuth(authRequest);
            AuthenticationResultType authenticationResultType = authResponse.getAuthenticationResult();
            String cognitoAccessToken = authenticationResultType.getAccessToken();
            whoAmIService.setCognitoAccessToken(cognitoAccessToken);

            Map<String, String> challengeParams = authResponse.getChallengeParameters();
            String cognitoUserIdForSrp = challengeParams.get("USER_ID_FOR_SRP");
            String cognitoUserAttributes = challengeParams.get("userAttributes");
            logger.debug("Cognito authenticated user ID: {} with user attributes: {}"
                    , cognitoUserIdForSrp, cognitoUserAttributes);
            return true;
        } catch (NotAuthorizedException nae) {
            logger.error("Invalid Cognito username/password provided for {}", username);
            return false;
        } catch (AWSCognitoIdentityProviderException acipe) {
            logger.error("Base exception for all service exceptions thrown by Amazon Cognito Identity Provider", acipe);
            return false;
        }
    }

1 个答案:

答案 0 :(得分:0)

我找到了使用STS的方法。更改此行:

<div>
   {someElementsConst}
   {getSomeElements()}
   <SomeElementsComponent/>
</div>

收件人:

AWSCognitoIdentityProvider awsCognitoIDPClient = createCognitoIDPClient();