AWS Cognito - Sign-in User Programmatically using Java

To programmatically sign in a user in Amazon Cognito using Java, you typically use the AWS SDK for Java. Here are the steps:

  1. First, add AWS Java SDK For Amazon Cognito Identity Provider Service dependency to your project.
  2. Sample Java code:
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProviderClientBuilder;
import com.amazonaws.services.cognitoidp.model.AdminInitiateAuthRequest;
import com.amazonaws.services.cognitoidp.model.AdminInitiateAuthResult;
import com.amazonaws.services.cognitoidp.model.AdminRespondToAuthChallengeRequest;
import com.amazonaws.services.cognitoidp.model.AdminRespondToAuthChallengeResult;
import com.amazonaws.services.cognitoidp.model.AuthFlowType;
import com.amazonaws.services.cognitoidp.model.AuthenticationResultType;
import com.amazonaws.services.cognitoidp.model.ChallengeNameType;

public class CognitoExample {

  public static void main(String args) {
    // AWS credentials
    String ACCESS_KEY = "AKIASI5XVTY2KVH46OND";
    String SECRET_KEY = "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";

    // Cognito credentials
    String clientId = "3uiat1ngjtgfu6v3sv0ha6786";
    String userPoolId = "us-east-1_c174bztKi";

    // Test user data
    String email = "testbuddy@example.com";
    String password = "Test123$";
    // New password is only required if the user status is FORCED_CHANGE_PASSWORD
    String newPassword = "";

    BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);

    AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion("us-east-1")
        .build();



    final Map<String, String> authParams = new HashMap<>();
    authParams.put("USERNAME", email);
    authParams.put("PASSWORD", password);

    final AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest();
    authRequest.withAuthFlow(AuthFlowType.ADMIN_NO_SRP_AUTH).withClientId(clientId)
        .withUserPoolId(userPoolId).withAuthParameters(authParams);

    try {
      AdminInitiateAuthResult result = cognitoClient.adminInitiateAuth(authRequest);

      AuthenticationResultType authenticationResult = null;

      if (result.getChallengeName() != null && !result.getChallengeName().isEmpty()) {

        System.out.println("Challenge Name is " + result.getChallengeName());

        if (result.getChallengeName().contentEquals("NEW_PASSWORD_REQUIRED")) {
          if (password == null) {
            System.out.println("User must change password " + result.getChallengeName());

          } else {

            final Map<String, String> challengeResponses = new HashMap<>();
            challengeResponses.put("USERNAME", email);
            challengeResponses.put("PASSWORD", password);
            // add new password
            challengeResponses.put("NEW_PASSWORD", newPassword);

            final AdminRespondToAuthChallengeRequest request =
                new AdminRespondToAuthChallengeRequest()
                    .withChallengeName(ChallengeNameType.NEW_PASSWORD_REQUIRED)
                    .withClientId(clientId).withUserPoolId(userPoolId)
                    .withChallengeResponses(challengeResponses).withSession(result.getSession());

            AdminRespondToAuthChallengeResult resultChallenge =
                cognitoClient.adminRespondToAuthChallenge(request);
            authenticationResult = resultChallenge.getAuthenticationResult();

            System.out.println(authenticationResult.getAccessToken());
            System.out.println(authenticationResult.getIdToken());
            System.out.println(authenticationResult.getRefreshToken());
            System.out.println(authenticationResult.getExpiresIn());
            System.out.println(authenticationResult.getTokenType());
          }

        } else {
          System.out.println("User has other challenge " + result.getChallengeName());
        }
      } else {

        System.out.println("User has no challenge");
        authenticationResult = result.getAuthenticationResult();
   
        System.out.println(authenticationResult.getAccessToken());
        System.out.println(authenticationResult.getIdToken());
        System.out.println(authenticationResult.getRefreshToken());
        System.out.println(authenticationResult.getExpiresIn());
        System.out.println(authenticationResult.getTokenType());
      }

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    cognitoClient.shutdown();
  }

}