AWS Cognito User Sign-in Java Sample Code

Add the Amazon Cognito Java SDK dependency to your Java project.

The code shows how to sign-in a user in AWS Cognito:


        //AWS credentials
        String ACCESS_KEY = "AKIASI5XVTR2BVL46OND";
        String SECRET_KEY = "csYwUXMeBUDqIEYSJNWoMAlzYnWQ75qRGw06jTML";

        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);

        AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder
                .standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withRegion("us-east-1").build();
        //Cognito credentials
        String clientId = "3uiat1ngjtgfu6v3sv0ha6786";
        String userPoolId = "us-east-1_mLMTsT974";
        
        String username = "testbuddy@example.com";
        String password = "Test123$";
        //New password is only required if the user status is FORCED_CHANGE_PASSWORD
        String newPassword = "";

        final Map<String, String> authParams = new HashMap<>();
        authParams.put("USERNAME", username);
        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", username);
                        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 {
                    throw new CustomException(
                            "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 (InvalidParameterException e) {
            System.out.println(e.getErrorMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        cognitoClient.shutdown();