我们一直在编写一些代码来测试我们的端点和身份验证过程。我们使用Cognito进行身份验证,我们的端点需要具有隐式授权流的访问令牌。
通过阅读亚马逊的文档,我们已经成功使用以下代码获取了openid令牌:
AmazonCognitoIdentity identityClient = new AmazonCognitoIdentityClient(
new BasicAWSCredentials("XXXXXXXXXXXXXXXXXXXXX",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
);
identityClient.setRegion(Region.getRegion(Regions.EU_WEST_1));
GetOpenIdTokenForDeveloperIdentityRequest request =
new GetOpenIdTokenForDeveloperIdentityRequest();
request.setIdentityPoolId("eu-west-1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Map<String,String> logins = new HashMap<>();
logins.put("acceptance-tests", "acceptance-tests");
request.setLogins(logins);
GetOpenIdTokenForDeveloperIdentityResult response =
identityClient.getOpenIdTokenForDeveloperIdentity(request);
String identityId = response.getIdentityId();
String token = response.getToken();
我们只是不知道如何将openid令牌交换为访问令牌以调用我们的端点。
也就是说,我们甚至不确定我们是否真的需要先获取一个openid令牌才能获取访问令牌。
在尝试使用下面的代码获取访问令牌之前,但我们的端点未接受我们获得的令牌。我们获得的令牌与通过cognito UI登录时获得的令牌不同。
final String clientId = "XXXXXXXXXXXXXXXXXXXXXXXXX";
final String region = "eu-west-1";
final String username = "USERNAME";
final String password = "PASSWORD";
AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder.standard()
.withRegion(region)
.build();
final Map<String, String> authParams = new HashMap<>();
authParams.put("USERNAME", username);
authParams.put("PASSWORD", password);
final InitiateAuthRequest authRequest = new InitiateAuthRequest();
authRequest.withAuthFlow(AuthFlowType.USER_SRP_AUTH)
.withClientId(clientId)
.withAuthParameters(authParams);
InitiateAuthResult result = cognitoClient.initiateAuth(authRequest);