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

…衆ロ難τιáo~ 提交于 2021-01-29 22:20:35

问题


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

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:


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<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());
    

    }

  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 = "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 ");
     }}
    


来源:https://stackoverflow.com/questions/63929294/how-to-configure-aws-user-cognito-authentication-flow-for-generating-identity-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!