Amazon Cognito 开发人员使用 Java SDK 验证身份

Amazon Cognito developer authenticated identity with Java SDK

我正在尝试使用经开发人员验证的 Cognito 身份对 java 应用程序进行 AWS 服务的验证。这在 AWS 移动 SDK (documentation) 中非常简单,但我似乎无法在 Java SDK 中找到等效的 类。

我遇到的主要问题是 Java SDK 类(例如 WebIdentityFederationSessionCredentialsProvider)要求客户端代码知道所承担角色的 arn。对于移动 SDK,它使用为联合身份配置的角色。这就是我喜欢做的,但 Java SDK 似乎没有支持 类。

如果这是你想要的路线,你可以在 IAM 控制台中找到这个名为 Cognito_(Auth|Unauth)_DefaultRole 的角色。这些是 Cognito 生成并链接到您的池的内容,您可以从那里获取 ARN。

This blog post 可能会有一些帮助。 SDK 用于与 Cognito 通信以获取凭据的所有 API 都在 Java SDK 中公开,您只需要使用自己的后端来获取令牌本身。拥有它后,您可以像通常使用其他提供商一样设置登录名,这一切都会起作用。

Jeff 的最后一条评论让我找到了答案。谢谢杰夫!

String cognitoIdentityId = "your user's identity id";
String openIdToken = "open id token for the user created on backend";

Map<String,String> logins = new HashMap<>();
logins.put("cognito-identity.amazonaws.com", openIdToken);
GetCredentialsForIdentityRequest getCredentialsRequest =
    new GetCredentialsForIdentityRequest()
    .withIdentityId(cognitoIdentityId)
    .withLogins(logins);
AmazonCognitoIdentityClient cognitoIdentityClient = new AmazonCognitoIdentityClient();
GetCredentialsForIdentityResult getCredentialsResult = cognitoIdentityClient.getCredentialsForIdentity(getCredentialsRequest);
Credentials credentials = getCredentialsResult.getCredentials();
AWSSessionCredentials sessionCredentials = new BasicSessionCredentials(
    credentials.getAccessKeyId(),
    credentials.getSecretKey(),
    credentials.getSessionToken()
);

AmazonS3Client s3Client = new AmazonS3Client(sessionCredentials);
...