Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CognitoIdentityProviderClient.adminInitiateAuth is consistently failing. What is missing? #5134

Open
ipsi-apant opened this issue Apr 23, 2024 · 3 comments
Assignees
Labels
bug This issue is a bug. guidance Question that needs advice or information.

Comments

@ipsi-apant
Copy link

Describe the bug

I have created a Cognito user pool. Added two app clients. One having secret another without secret. Also, added a user to the pool. The documents I am referring mentioned in the Additional Information/Context

Use case

We are planning to integrate Cognito for backend app as auth mechanism. The request contains username/password (due to backward compatibility for legacy systems). Based on the username/password we need to generate an access token using Cognito APIs.

Behavior

In the following code sample listUsers function is working. However, call to adminInitiateAuth always return null response.

Error

java.lang.NullPointerException: Cannot invoke "software.amazon.awssdk.services.cognitoidentityprovider.model.AuthenticationResultType.accessToken()" because the return value of "software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse.authenticationResult()" is null

Code sample

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersRequest;

@Slf4j
public class CognitoPoc {

  private static final String userPool = "ap-southeast-2_mypoolid";

  public void adminAuth(Map<String, String> params) {

    try (CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                                                                                    .region(Region.AP_SOUTHEAST_2)
                                                                                    .build()) {

      listUsers(cognitoClient); // this works

      log.info("----------------------------------------");

      log.info("CognitoPoc.adminAuth: Access token for user");

      adminUserPasswordAuth(cognitoClient, params);
    }

  }

  private void adminUserPasswordAuth(CognitoIdentityProviderClient cognitoClient,
                                     Map<String, String> params) {
    try {
      log.info("Access token by ADMIN_USER_PASSWORD_AUTH flow");

      String username = params.get("username");
      String password = params.get("password");
      String clientId = params.get("clientId");
      String secret = params.get("secret");

      Map<String, String> authParameters = new HashMap<>();
      authParameters.put("USERNAME", username);
      authParameters.put("PASSWORD", password);
      Optional.ofNullable(secret)
              .ifPresent(hash -> authParameters.put("SECRET_HASH", hash));

      AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest
          .builder()
          .clientId(clientId)
          .userPoolId(userPool)
          .authParameters(authParameters)
          .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
          .build();

      AdminInitiateAuthResponse adminFlowResponse = cognitoClient.adminInitiateAuth(authRequest);

      log.info("Admin flow adminFlowResponse");
      logResponse(adminFlowResponse);

    } catch (CognitoIdentityProviderException e) {
      log.error("CognitoIdentityProviderException: {}", e.getMessage());
    }
  }

  private void logResponse(AdminInitiateAuthResponse response) {
    log.info("Authentication result: {}", response.authenticationResult());
    log.info("access token: {}",
             response.authenticationResult()
                     .accessToken()
    );
    log.info("Challenge parameters: {}", response.challengeParameters());
    log.info("Session: {}", response.session());
    log.info("Challenge name: {}", response.challengeName());
  }

  private void listUsers(CognitoIdentityProviderClient cognitoClient) {

    log.info("CognitoPocAssist.listUsers: Listing users");

    cognitoClient.listUsers(
                     ListUsersRequest.builder()
                                     .limit(2)
                                     .userPoolId(userPool)
                                     .build()
                 )
                 .users()
                 .forEach(userType -> log.info("User: {}", userType));
  }
}

Expected Behavior

As per AWS Cognito document, it should return a response having an access token. Not sure what is missing?

AdminInitiateAuthResponse adminFlowResponse = cognitoClient.adminInitiateAuth(authRequest);

Current Behavior

Following invocation always return null response

AdminInitiateAuthResponse adminFlowResponse = cognitoClient.adminInitiateAuth(authRequest);

Reproduction Steps

  1. Create a Cognito user pool
  2. Add app client for newly created pool
  3. Add user for newly created pool
  4. Create a map with user-pool-id, username, clientId, secret_hash (optional) for ADMIN_USER_PASSWORD_AUTH type
  5. Run the code sample

Possible Solution

Not sure but need some advise on what is missing, although the code is based on documentation.

Additional Information/Context

Referring these documents:

AWS Java SDK version used

2.24.1

JDK version used

21

Operating System and version

ubuntu2204-2023-07-25

@ipsi-apant ipsi-apant added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Apr 23, 2024
@bhoradc bhoradc self-assigned this Apr 25, 2024
@bhoradc bhoradc added guidance Question that needs advice or information. and removed needs-triage This issue or PR still needs to be triaged. labels Apr 25, 2024
@bhoradc
Copy link

bhoradc commented Apr 26, 2024

Hi @ipsi-apant,

I am unable to reproduce the issue. Using the code sample you provided. I do get the access token successfully.

Can you please check if the Confirmation status for the Cognito User is Confirmed and not Force change password. You may get the NULL response when the ChallengeName="NEW_PASSWORD_REQUIRED".

You can respond to the challenge using adminRespondToAuthChallenge(). Here's the link to the code example for this use-case.

Let me know if this helps.

Regards,
Chaitanya

@bhoradc bhoradc added the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 10 days. label Apr 26, 2024
Copy link

github-actions bot commented May 6, 2024

It looks like this issue has not been active for more than five days. In the absence of more information, we will be closing this issue soon. If you find that this is still a problem, please add a comment to prevent automatic closure, or if the issue is already closed please feel free to reopen it.

@github-actions github-actions bot added the closing-soon This issue will close in 4 days unless further comments are made. label May 6, 2024
@ipsi-apant
Copy link
Author

ipsi-apant commented May 6, 2024

Hi @ipsi-apant,

I am unable to reproduce the issue. Using the code sample you provided. I do get the access token successfully.

Can you please check if the Confirmation status for the Cognito User is Confirmed and not Force change password. You may get the NULL response when the ChallengeName="NEW_PASSWORD_REQUIRED".

You can respond to the challenge using adminRespondToAuthChallenge(). Here's the link to the code example for this use-case.

Let me know if this helps.

Regards, Chaitanya

The user confirmation status is already Confirmed. I will try again.

@github-actions github-actions bot removed closing-soon This issue will close in 4 days unless further comments are made. response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 10 days. labels May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug This issue is a bug. guidance Question that needs advice or information.
Projects
None yet
Development

No branches or pull requests

2 participants