AWS Cognito Create a User Programmatically Java Sample Code

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

The following code creates a new user with status CONFIRMED to your Cognito user pool:


        //AWS credentials
        String ACCESS_KEY = "AKIASI5XVTY2KVH46OND";
        String SECRET_KEY = "+sYwUXMeBUDqI/YvJNfoMAlzYnWQ75qRGw06jTML";
        String userPoolId = "us-east-1_c174bztKi";

        BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);

        AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder
                .standard().withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withRegion("us-east-1").build();
        
        //Test user data
        String email = "testbuddy@example.com";
        String username = "testbuddy";
        String password = "Test123$";
        
        try {
            AttributeType emailAttr = new AttributeType().withName("email").withValue(email);
            AttributeType emailVerifiedAttr =
                    new AttributeType().withName("email_verified").withValue("false");

            AdminCreateUserRequest userRequest =
                    new AdminCreateUserRequest().withUserPoolId(userPoolId).withUsername(username)
                            .withTemporaryPassword(password)
                            .withUserAttributes(emailAttr, emailVerifiedAttr)
                            .withMessageAction(MessageActionType.SUPPRESS);

            AdminCreateUserResult createUserResult = cognitoClient.adminCreateUser(userRequest);

            System.out.println("User " + createUserResult.getUser().getUsername()
                    + " is created. Status: " + createUserResult.getUser().getUserStatus());
            
            // Make the password permanent and not temporary
            AdminSetUserPasswordRequest adminSetUserPasswordRequest =
                    new AdminSetUserPasswordRequest().withUsername(username)
                            .withUserPoolId(userPoolId).withPassword(password).withPermanent(true);
            cognitoClient.adminSetUserPassword(adminSetUserPasswordRequest);
        } catch (AWSCognitoIdentityProviderException e) {
            System.out.println(e.getErrorMessage());
        } catch (Exception e) {
            System.out.println(e);
        }