Skip to content

How do I automatically confirm users in Amazon Cognito?

6 minute read
5

I want to confirm users and then verify their email addresses and phone numbers automatically without using one-time-passwords (OTPs).

Short description

When a user signs up with an Amazon Cognito user pool, the user must typically verify their email address or phone number. Amazon Cognito sends an OTP to the user's email address or phone number for verification. To automatically confirm a user without OTP verification, use an AWS Lambda function with the pre sign-up Lambda trigger.

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Create a Lambda function

Complete the following steps:

  1. Create a Lambda function to handle the pre sign-up event that's triggered when a user is created. The following example Python code confirms the user and their attributes, such as the email address and phone number. 

    import json 
    def lambda_handler(event, context): 
        # Confirm the user 
        event['response']['autoConfirmUser'] = True 
        # Set the email as verified if it is in the request 
        if 'email' in event['request']['userAttributes']: 
            event['response']['autoVerifyEmail'] = True 
        # Set the phone number as verified if it is in the request 
        if 'phone_number' in event['request']['userAttributes']: 
            event['response']['autoVerifyPhone'] = True 
        # Return to Amazon Cognito 
        return event
  2. Set up a testing event in the Lambda function with data that's relevant to the pre sign-up Lambda trigger. The following is an example test event for the sample Python code from step 1:

    {
      "request": { 
        "userAttributes": { 
          "email": "[email@example.com](mailto:email@example.com)", 
          "phone_number": "5550100" 
        } 
      }, 
      "response": {} 
    }
  3. Run the test and confirm that the response includes the auto-confirmation attributes.

Create an Amazon Cognito user pool

Complete the following steps:

  1. Create a new Amazon Cognito user pool, or select an existing user pool.
  2. In your user pool, add the pre sign-up Lambda trigger and select the Lambda function that you created.
  3. Verify that you configured the pre sign-up Lambda trigger in your user pool. When a new user signs up, Amazon Cognito passes the event information to the Lambda function. The Lambda function returns the event object to Amazon Cognito with the confirmation and verification values in the response. The following is an example response:
    {
      "request": {
        "userAttributes": {
          "email": "email@example.com",
          "phone_number": "5550100"
        }
      },
      "response": {
        "autoConfirmUser": true,
        "autoVerifyEmail": true,
        "autoVerifyPhone": true
      }
    }

Note: If a new user signs up with a preexisting phone number or email address alias, then the alias moves to the new user. Amazon Cognito transfers the alias to the new user and marks the previous user's attributes as unverified. To prevent these changes, invoke the ListUsers API to compare new user attributes against existing users before confirmation.

Sign up the Amazon Cognito user

Use the Amazon Cognito hosted UI or invoke the SignUp API to sign up as a new user.

Use the Amazon Cognito hosted UI

Complete the following steps:

  1. In the Amazon Cognito hosted UI, sign up as a new user. Make sure to provide all required attributes. After you sign up, you're redirected to the callback URL without OTP verification.
  2. Verify your user attributes and confirm that the attributes are set to the following values:
    Account status is set to Enabled/CONFIRMED
    email_verified is set to true
    phone_number_verified is set to true

Use the AWS CLI

Complete the following steps:

  1. Compute the secret hash using the app client ID, the client secret, and the user name of the user in the Amazon Cognito user pool.

  2. In the AWS CLI, invoke the SignUp API to create a user.
    Example sign-up command:

    aws cognito-idp sign-up --client-id example_client_id --secret-hash example_secret_hash --username example_user_name --password example_password --user-attributes [Name="email",Value="email@example.com](mailto:Name=)" Name="phone_number",Value="5550100" 

    Note: Replace example_client_id with your client ID, example_secret_hash with your secret hash, example_user_name with your username, and example_password with your password.

  3. Install Python. For more information, see Download the latest version for Windows on the Python website.

  4. Save the following example Python script as a .py file:

    import base64, hashlib, hmac, argparse 
    parser = argparse.ArgumentParser() 
    parser.add_argument("--username", required=True) 
    parser.add_argument("--appclientid", required=True) 
    parser.add_argument("--appclientsecret", required=True) 
    args = parser.parse_args() 
    message = bytes(args.username + args.appclientid, 'utf-8') 
    key = bytes(args.appclientsecret, 'utf-8') 
    secret_hash = base64.b64encode(hmac.new(key, message, digestmod=hashlib.sha256).digest()).decode() 
    print('SecretHash: {}'.format(secret_hash))

    Note: Replace username, with the user name of the user in the user pool. Replace AppClientId, with your user pool's app client ID and AppClientSecret with your app client secret.

    For help, run following command:

    python3 secret\_hash.py -help.
  5. Use the following command to obtain the computed secret hash from the Python script:
    Example command:

    python3 secret_hash.py --username example_user_name --appclientid example_app_client_id --appclientsecret example_app_client_secret

An automatically confirmed user example

Complete the following steps:

  1. Run your Python script that uses the user name, app client ID, and client secret to compute the secret hash.

    python3 secret_hash.py --username example_user_name --appclientid 11122223333 --appclientsecret je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

    Note: Replace example_user_name with your username, appclientID with your app client ID, and appclientsecret with your app client secret.
    Output:

    SecretHash: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  2. Create an Amazon Cognito user by invoking the SignUp API.

    aws cognito-idp sign-up --client-id 7morqrabcdEXAMPLE_ID --secret-hash wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY = --username example_user_name --password Password1@ --user-attributes [Name='email',Value='email@example.com](mailto:Name='email',Value='email@example.com)' Name='phone_number',Value='5550100'

    Example output:

    { 
     "UserConfirmed": true, 
     "UserSub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" 
    }
  3. To verify the status of user attributes, invoke the AdminGetUser API.

    aws cognito-idp admin-get-user --user-pool-id us-east-1_I 111122223333 --username example_user_name

    Note: Replace us-east-1_I111122223333 with your Cognito User Pool ID. Replace example_user_name with the username of the user you want to retrieve information for.
    Example output:

    {
            "Username": "example_user_name",
            "UserAttributes": [
              { "Name": "sub", "Value": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
       },
              { "Name": "email_verified", "Value": "true" },
              { "Name": "phone_number_verified", "Value": "true" },
              { "Name": "phone_number", "Value": "+15550100" },
              { "Name": "email", "Value": "email@example.com" }
            ],
            "UserCreateDate": "2022-12-12T11:54:12.988000+00:00",
            "UserLastModifiedDate": "2022-12-12T11:54:12.988000+00:00",
            "Enabled": true,
            "UserStatus": "CONFIRMED"
          }
     

The final output confirms that Amazon Cognito verified the user without external OTP verification.

AWS OFFICIALUpdated 4 months ago