如何在Java sdk后端中配置AWS用户认知身份验证流程以生成身份令牌和访问令牌? [英] How to configure AWS user cognito authentication flow for generating identity token,access token in Java sdk backend?

查看:114
本文介绍了如何在Java sdk后端中配置AWS用户认知身份验证流程以生成身份令牌和访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我正在使用AWS Cognito身份验证进行签名机制.为了获取凭据(访问,秘密和会话令牌),我们需要获取身份令牌.
  2. 我正在获取用户名,密码,clientId,userPoolId,identityPoolId信息.但是,当我尝试使用USER_PASSWORD_AUTH作为身份验证流类型生成ID令牌时,出现以下错误 原因:com.amazonaws.services.cognitoidp.model.AWSCognitoIdentityProviderException:缺少身份验证令牌(服务:AWSCognitoIdentityProvider;状态代码:400;错误代码:MissingAuthenticationTokenException;请求ID :;代理:null)

下面是代码:

AnonymousAWSCredentials awsCreds = new AnonymousAWSCredentials();

    AWSCognitoIdentityProvider provider = AWSCognitoIdentityProviderClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion(//region)
            .build();
           

    AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
            .withAuthFlow(AuthFlowType.USER_PASSWORD_AUTH)
            .withClientId("")
            .withUserPoolId("")
            .withAuthParameters(map);
    Map<String,String> map = new HashMap<>();
    map.put("USERNAME","");
    map.put("PASSWORD","");

这里的地图将具有用户名和密码.

Here map will have username and password.

有人可以提供有关如何在Java中配置身份验证以生成ID令牌和访问令牌的帮助吗?在此先感谢!

Can someone help on how to configure authentication in Java in order to generate the id token and access token? Thanks in advance!!

推荐答案

您的代码可能如下所示.请注意:

Your code may look like below. Please note that:

  1. 使用ADMIN_USER_PASSWORD_AUTH流进行身份验证.请参见 AdminInitiateAuth

在Cognito中,在客户端设置的身份验证流程配置"部分下,应该启用下一个选项为管理员API启用用户名密码auth进行身份验证(ALLOW_ADMIN_USER_PASSWORD_AUTH)" .

In Cognito, in client settings, under section "Auth Flows Configuration" the next option should be enabled "Enable username password auth for admin APIs for authentication (ALLOW_ADMIN_USER_PASSWORD_AUTH)".

 public static void auth(String username, String password) {

 AwsBasicCredentials awsCreds = AwsBasicCredentials.create(AWS_KEY,
         AWS_SECRET);

 CognitoIdentityProviderClient identityProviderClient =
         CognitoIdentityProviderClient.builder()
                 .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                 .region(Region.of(REGION))
                 .build();

 final Map<String, String> authParams = new HashMap<>();
 authParams.put("USERNAME", username);
 authParams.put("PASSWORD", password);
 authParams.put("SECRET_HASH", calculateSecretHash(CLIENT_ID,
         CLIENT_SECRET, username));

 final AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder()
         .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
         .clientId(CLIENT_ID)
         .userPoolId(POOL_ID)
         .authParameters(authParams)
         .build();

 AdminInitiateAuthResponse result = identityProviderClient.adminInitiateAuth(authRequest);

 System.out.println(result.authenticationResult().accessToken());
 System.out.println(result.authenticationResult().idToken());

}

方法calculateSecretHash来自AWS文档注册并确认用户帐户:

Method calculateSecretHash is taken from AWS Documentation Signing Up and Confirming User Accounts:

 private static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) {
 final String HMAC_SHA256_ALGORITHM = "HmacSHA256";

 SecretKeySpec signingKey = new SecretKeySpec(
         userPoolClientSecret.getBytes(StandardCharsets.UTF_8),
         HMAC_SHA256_ALGORITHM);
 try {
     Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
     mac.init(signingKey);
     mac.update(userName.getBytes(StandardCharsets.UTF_8));
     byte[] rawHmac = mac.doFinal(userPoolClientId.getBytes(StandardCharsets.UTF_8));
     return Base64.getEncoder().encodeToString(rawHmac);
 } catch (Exception e) {
     throw new RuntimeException("Error while calculating ");
 }}

这篇关于如何在Java sdk后端中配置AWS用户认知身份验证流程以生成身份令牌和访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆