- 我在AWS帐户acc-1上有一个Cognito用户池,在acc-2上运行一个Java代码,它使用"adminInitiateAuth"进行身份验证,由于某些原因,我无法使用clientInitiateAuth
- 我在acc-1上创建了一个跨帐户角色,由我在acc-2上的Java代码承担
问题:当我向Cognito发送身份验证请求时,我如何承担该角色?是否可以使用withRoleArn()
?
我看到了这个页面,它解释了如何"使用API网关控制台为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;
}
}
我发现了如何使用STS来实现这一点。更改此行:
AWSCognitoIdentityProvider awsCognitoIDPClient = createCognitoIDPClient();
至:
String roleARN= "YOUR_CROSS_ACCOUNT_ROLE_ARN";
String roleSessionName = "GIVE_A_SESSION_NAME";
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder
.standard()
.withCredentials(new ProfileCredentialsProvider())
.build();
AssumeRoleRequest roleRequest = new AssumeRoleRequest()
.withRoleArn(roleARN)
.withRoleSessionName(roleSessionName);
AssumeRoleResult roleResponse = stsClient.assumeRole(roleRequest);
Credentials sessionCredentials = roleResponse.getCredentials();
BasicSessionCredentials awsCredentials = new BasicSessionCredentials(
sessionCredentials.getAccessKeyId(),
sessionCredentials.getSecretAccessKey(),
sessionCredentials.getSessionToken());
AWSCognitoIdentityProvider cognitoIPCB = AWSCognitoIdentityProviderClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.build();