How to configure AWS user cognito authentication flow for generating identity token,access token in Java sdk backend?

huangapple go评论76阅读模式
英文:

How to configure AWS user cognito authentication flow for generating identity token,access token in Java sdk backend?

问题

  1. 我正在使用 AWS Cognito 认证进行签名机制。为了获取凭证(访问凭证、秘密凭证和会话令牌),我们需要获取身份令牌。
  2. 我拥有用户名、密码、客户端 ID、用户池 ID、身份池 ID 信息。然而,当我尝试使用 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", "");

在这里,map 将包含用户名和密码。

有人可以帮助我如何在 Java 中配置身份验证以生成 ID 令牌和访问令牌吗?提前谢谢!

英文:
  1. I am using AWS Cognito authentication for signing mechanism. In order to obtain the credentials(access,secret and session token), we need to obtain identity token.
  2. I am having username,password,clientId,userPoolId,identityPoolId information. However,when I try to generate the id token using USER_PASSWORD_AUTH as auth flow type I am getting the below error
    Caused by: com.amazonaws.services.cognitoidp.model.AWSCognitoIdentityProviderException: Missing Authentication Token (Service: AWSCognitoIdentityProvider; Status Code: 400; Error Code: MissingAuthenticationTokenException; Request ID: ; Proxy: null)

Below is the code:

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(&quot;&quot;)
            .withUserPoolId(&quot;&quot;)
            .withAuthParameters(map);
    Map&lt;String,String&gt; map = new HashMap&lt;&gt;();
    map.put(&quot;USERNAME&quot;,&quot;&quot;);
    map.put(&quot;PASSWORD&quot;,&quot;&quot;);

Here map will have username and password.

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

答案1

得分: 4

你的代码可能如下所示。请注意:

  1. 用于身份验证的是ADMIN_USER_PASSWORD_AUTH流程。请参阅AdminInitiateAuth

  2. 在Cognito中,在客户端设置中,在“Auth Flows Configuration”部分下,下一个选项应启用“为管理员API启用用户名密码身份验证(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());
}

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 ");
    }
}
  1. 方法calculateSecretHash取自AWS文档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 ");
    }
}
英文:

Your code may look like below. Please note that:

  1. For authentication is used ADMIN_USER_PASSWORD_AUTH flow. Please see
    AdminInitiateAuth

  2. 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&lt;String, String&gt; authParams = new HashMap&lt;&gt;();
    authParams.put(&quot;USERNAME&quot;, username);
    authParams.put(&quot;PASSWORD&quot;, password);
    authParams.put(&quot;SECRET_HASH&quot;, 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());
    

    }

  3. 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 = &quot;HmacSHA256&quot;;
    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(&quot;Error while calculating &quot;);
    }}
    

huangapple
  • 本文由 发表于 2020年9月17日 07:37:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63929294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定