Customizing user pool workflows with Lambda triggers (original) (raw)

Amazon Cognito works with AWS Lambda functions to modify the authentication behavior of your user pool. You can configure your user pool to automatically invoke Lambda functions before their first sign-up, after they complete authentication, and at several stages in between. Your functions can modify the default behavior of your authentication flow, make API requests to modify your user pool or other AWS resources, and communicate with external systems. The code in your Lambda functions is your own. Amazon Cognito sends event data to your function, waits for the function to process the data, and in most cases anticipates a response event that reflects any changes you want to make to the session.

Within the system of request and response events, you can introduce your own authentication challenges, migrate users between your user pool and another identity store, customize messages, and modify JSON web tokens (JWTs).

Lambda triggers can customize the response that Amazon Cognito delivers to your user after they initiate an action in your user pool. For example, you can prevent sign-in by a user who would otherwise succeed. They can also perform runtime operations against your AWS environment, external APIs, databases, or identity stores. The migrate user trigger, for example, can combine external action with a change in Amazon Cognito: you can look up user information in an external directory, then set attributes on a new user based on that external information.

When you have a Lambda trigger assigned to your user pool, Amazon Cognito interrupts its default flow to request information from your function. Amazon Cognito generates a JSON event and passes it to your function. The event contains information about your user's request to create a user account, sign in, reset a password, or update an attribute. Your function then has an opportunity to take action, or to send the event back unmodified.

The following table summarizes some of the ways you can use Lambda triggers to customize user pool operations:

Topics

Things to know about Lambda triggers

When you are preparing your user pools for Lambda functions, consider the following:

Example Lambda Resource-Based Policy

The following example Lambda resource-based policy grants Amazon Cognito a limited ability to invoke a Lambda function. Amazon Cognito can only invoke the function when it does so on behalf of both the user pool in the aws:SourceArn condition and the account in the aws:SourceAccount condition.

{  
    "Version": "2012-10-17",  
    "Id": "default",  
    "Statement": [  
        {  
            "Sid": "lambda-allow-cognito",  
            "Effect": "Allow",  
            "Principal": {  
                "Service": "cognito-idp.amazonaws.com"  
            },  
            "Action": "lambda:InvokeFunction",  
            "Resource": "<your Lambda function ARN>",  
            "Condition": {  
                "StringEquals": {  
                    "AWS:SourceAccount": "<your account number>"  
                },  
                "ArnLike": {  
                    "AWS:SourceArn": "<your user pool ARN>"  
                }  
            }  
        }  
    ]  
}  

Add a user pool Lambda trigger

To add a user pool Lambda trigger with the console
  1. Use the Lambda console to create a Lambda function. For more information on Lambda functions, see theAWS Lambda Developer Guide.
  2. Go to the Amazon Cognito console, and then choose User Pools.
  3. Choose an existing user pool from the list, or create a user pool.
  4. Choose the Extensions menu and locate Lambda triggers.
  5. Choose Add a Lambda trigger.
  6. Select a Lambda trigger Category based on the stage of authentication that you want to customize.
  7. Select Assign Lambda function and select a function in the same AWS Region as your user pool.
Note

If your AWS Identity and Access Management (IAM) credentials have permission to update the Lambda function, Amazon Cognito adds a Lambda resource-based policy. With this policy, Amazon Cognito can invoke the function that you select. If the signed-in credentials do not have sufficient IAM permissions, you must update the resource-based policy separately. For more information, see Things to know about Lambda triggers. 8. Choose Save changes. 9. You can use CloudWatch in the Lambda console to log your Lambda function . For more information, see Accessing CloudWatch Logs for Lambda.

Amazon Cognito passes event information to your Lambda function. The Lambda function returns the same event object back to Amazon Cognito with any changes in the response. If your function returns the input event without modification, Amazon Cognito proceed with default behavior. The following shows the parameters that are common to all Lambda trigger input events. For trigger-specific event syntax, review the event schema on the section of this guide for each trigger.

JSON

{
    "version": "string",
    "triggerSource": "string",
    "region": AWSRegion,
    "userPoolId": "string",
    "userName": "string",
    "callerContext": 
        {
            "awsSdkVersion": "string",
            "clientId": "string"
        },
    "request":
        {
            "userAttributes": {
                "string": "string",
                ....
            }
        },
    "response": {}
}

version

The version number of your Lambda function.

triggerSource

The name of the event that triggered the Lambda function. For a description of each triggerSource see Connecting Lambda triggers to user pool functional operations.

region

The AWS Region as an AWSRegion instance.

userPoolId

The ID of the user pool.

userName

The current user's username.

callerContext

Metadata about the request and the code environment. It contains the fields awsSdkVersion andclientId.

awsSdkVersion

The version of the AWS SDK that generated the request.

**clientId

The ID of the user pool app client.

request

Details of your user's API request. It includes the following fields, and any request parameters that are particular to the trigger. For example, an event that Amazon Cognito sends to a pre-authentication trigger will also contain auserNotFound parameter. You can process the value of this parameter to take a custom action when your user tries to sign in with an unregistered username.

userAttributes

One or more key-value pairs of user attribute names and values, for example "email": "john@example.com".

response

This parameter doesn't contain any information in the original request. Your Lambda function must return the entire event to Amazon Cognito, and add any return parameters to the response. To see what return parameters your function can include, refer to the documentation for the trigger that you want to use.

You can submit custom parameters to your Lambda trigger functions in API operations andToken endpoint requests. With client metadata, your application can collect additional information about the environment where requests originate. When you pass client metadata to your Lambda functions, they can process the additional data and make use of it in logging or customization of authentication flows. Client metadata is string pairs of your choosing and design in a JSON key-value format.

Client metadata example use cases

Here is an example of passing client metadata to the pre sign-up trigger.

SignUp request

The following is an example SignUp request with client metadata that Amazon Cognito passes to a pre sign-up trigger.

POST HTTP/1.1
Host: cognito-idp.us-east-1.amazonaws.com
X-Amz-Date: 20230613T200059Z
Accept-Encoding: gzip, deflate, br
X-Amz-Target: AWSCognitoIdentityProviderService.SignUp
User-Agent: <UserAgentString>
Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<Signature>
Content-Length: <PayloadSizeBytes>

{
    "ClientId": "1example23456789",
    "Username": "mary_major",
    "Password": "<Password>",
    "SecretHash": "<Secret hash>",
    "ClientMetadata": { 
        "IpAddress" : "192.0.2.252",
        "GeoLocation" : "Netherlands (Kingdom of the) [NL]"
    }
    "UserAttributes": [
        {
            "Name": "name",
            "Value": "Mary"
        },
        {
            "Name": "email",
            "Value": "mary_major@example.com"
        },
        {
            "Name": "phone_number",
            "Value": "+12065551212"
        }
    ],
}

Lambda trigger input event

The request results in the following request body to your pre sign-up function.

{
    "callerContext": {
        "awsSdkVersion": "aws-sdk-unknown-unknown",
        "clientId": "1example23456789"
    },
    "region": "us-west-2",
    "request": {
        "clientMetadata": {
            "GeoLocation": "Netherlands (Kingdom of the) [NL]",
            "IpAddress": "192.0.2.252"
        },
        "userAttributes": {
            "email": "mary_major@example.com",
            "name": "Mary",
            "phone_number": "+12065551212"
        },
        "validationData": null
    },
    "response": {
        "autoConfirmUser": false,
        "autoVerifyEmail": false,
        "autoVerifyPhone": false
    },
    "triggerSource": "PreSignUp_SignUp",
    "userName": "mary_major2",
    "userPoolId": "us-west-2_EXAMPLE",
    "version": "1"
}
Client metadata for machine-to-machine (M2M) client credentials

You can pass client metadata in M2M requests. Client metadata is additional information from a user or application environment that can contribute to the outcomes of a Pre token generation Lambda trigger. In authentication operations with a user principal, you can pass client metadata to the pre token generation trigger in the body of AdminRespondToAuthChallenge and RespondToAuthChallenge API requests. Because applications conduct the flow for generation of access tokens for M2M with direct requests to the Token endpoint, they have a different model. In the POST body of token requests for client credentials, pass anaws_client_metadata parameter with the client metadata object URL-encoded (x-www-form-urlencoded) to string. For an example request, see Client credentials with basic authorization. The following is an example parameter that passes the key-value pairs{"environment": "dev", "language": "en-US"}.

aws_client_metadata=%7B%22environment%22%3A%20%22dev%22,%20%22language%22%3A%20%22en-US%22%7D
Temporary user attributes: validationData

Some authentication operations also have a validationData parameter. Like client metadata, this is an opportunity to pass external information that Amazon Cognito doesn't automatically gather to Lambda triggers. The validation data field is intended to provide your Lambda function witth additional user context in sign-up and sign-in operations. SignUp and AdminCreateUser pass validationData to the pre sign-up trigger. InitiateAuth and AdminInitiateAuth pass ClientMetadata in the API request body as validationData in the input event to the pre authentication andmigrate user triggers.

To map API operations to the functions that they can pass client metadata to, refer to the trigger source sections that follow.

Connecting API operations to Lambda triggers

The following sections describe the Lambda triggers that Amazon Cognito invokes from the activity in your user pool.

When your app signs in users through the Amazon Cognito user pools API, managed login, or user pool endpoints, Amazon Cognito invokes your Lambda functions based on the session context. For more information about the Amazon Cognito user pools API and user pool endpoints, see Understanding API, OIDC, and managed login pages authentication. The tables in the sections that follow describe events that cause Amazon Cognito to invoke a function, and the triggerSource string that Amazon Cognito includes in the request.

Topics

Lambda triggers in the Amazon Cognito API

The following table describes the source strings for the Lambda triggers that Amazon Cognito can invoke when your app creates, signs in, or updates a local user.

Local user trigger sources in the Amazon Cognito API

API operation Lambda trigger Trigger source
AdminCreateUser Pre sign-up PreSignUp_AdminCreateUser
Pre token generation TokenGeneration_NewPasswordChallenge
Custom message CustomMessage_AdminCreateUser
Custom email sender CustomEmailSender_AdminCreateUser
Custom SMS sender CustomSMSSender_AdminCreateUser
SignUp Pre sign-up PreSignUp_SignUp
Custom message CustomMessage_SignUp
Custom email sender CustomEmailSender_SignUp
Custom SMS sender CustomSMSSender_SignUp
ConfirmSignUp AdminConfirmSignUp Post confirmation PostConfirmation_ConfirmSignUp
InitiateAuth AdminInitiateAuth Pre authentication PreAuthentication_Authentication
Define auth challenge DefineAuthChallenge_Authentication
Create auth challenge CreateAuthChallenge_Authentication
Pre token generation TokenGeneration_Authentication TokenGeneration_AuthenticateDevice TokenGeneration_RefreshTokens
Migrate user UserMigration_Authentication
Custom message CustomMessage_Authentication
Custom email sender CustomEmailSender_AccountTakeOverNotification CustomEmailSender_Authentication
Custom SMS sender CustomSMSSender_Authentication
ForgotPassword Migrate user UserMigration_ForgotPassword
Custom message CustomMessage_ForgotPassword
Custom email sender CustomEmailSender_ForgotPassword
Custom SMS sender CustomSMSSender_ForgotPassword
ConfirmForgotPassword Post confirmation PostConfirmation_ConfirmForgotPassword
UpdateUserAttributes AdminUpdateUserAttributes Custom message CustomMessage_UpdateUserAttribute
Custom email sender CustomEmailSender_UpdateUserAttribute
Custom SMS sender CustomSMSSender_UpdateUserAttribute
VerifyUserAttributes Custom message CustomMessage_VerifyUserAttribute
Custom email sender CustomEmailSender_VerifyUserAttribute
Custom SMS sender CustomSMSSender_VerifyUserAttribute
GetTokensFromRefreshToken Pre token generation TokenGeneration_Authentication

Lambda triggers for Amazon Cognito local users in managed login

The following table describes the source strings for the Lambda triggers that Amazon Cognito can invoke when a local user signs in to your user pool with managed login.

Local user trigger sources in managed login

Managed login URI Lambda trigger Trigger source
/signup Pre sign-up PreSignUp_SignUp
Custom message CustomMessage_SignUp
Custom email sender CustomEmailSender_SignUp
Custom SMS sender CustomSMSSender_SignUp
/confirmuser Post confirmation PostConfirmation_ConfirmSignUp
/login Pre authentication PreAuthentication_Authentication
Pre token generation TokenGeneration_Authentication TokenGeneration_AuthenticateDevice TokenGeneration_RefreshTokens
Migrate user UserMigration_Authentication
Custom message CustomMessage_Authentication
Custom email sender CustomEmailSender_AccountTakeOverNotification CustomEmailSender_Authentication
Custom SMS sender CustomSMSSender_Authentication
/forgotpassword Migrate user UserMigration_ForgotPassword
Custom message CustomMessage_ForgotPassword
Custom email sender CustomEmailSender_ForgotPassword
Custom SMS sender CustomSMSSender_ForgotPassword
/confirmforgotpassword Post confirmation PostConfirmation_ConfirmForgotPassword

Lambda triggers for federated users

You can use the following Lambda triggers to customize your user pool workflows for users who sign in with a federated provider.

Note

Federated users can use managed login to sign in, or you can generate a request to the Authorize endpoint that silently redirects them to their identity provider sign-in page. You can't sign in federated users with the Amazon Cognito user pools API.

Federated user trigger sources

Sign-in event Lambda trigger Trigger source
First sign-in Pre sign-up PreSignUp_ExternalProvider
Post confirmation PostConfirmation_ConfirmSignUp
Pre token generation TokenGeneration_HostedAuth
Subsequent sign-ins Pre authentication PreAuthentication_Authentication
Post authentication PostAuthentication_Authentication
Pre token generation TokenGeneration_HostedAuth

Federated sign-in does not invoke any Custom authentication challenge Lambda triggers, Migrate user Lambda trigger, Custom message Lambda trigger, or Custom sender Lambda triggers in your user pool.

Connecting Lambda triggers to user pool functional operations

Each Lambda trigger serves a functional role in your user pool. For example, a trigger can modify your sign-up flow, or add a custom authentication challenge. The event that Amazon Cognito sends to a Lambda function can reflect one of multiple actions that make up that functional role. For example, Amazon Cognito invokes a pre sign-up trigger when your user signs up, and when you create a user. Each of these different cases for the same functional role has its own triggerSource value. Your Lambda function can process incoming events differently based on the operation that invoked it.

Amazon Cognito also invokes all assigned functions when an event corresponds to a trigger source. For example, when a user signs in to a user pool where you assigned migrate user and pre authentication triggers, they activate both.

Sign-up, confirmation, and sign-in (authentication) triggers

Trigger triggerSource value Event
Pre sign-up PreSignUp_SignUp Pre sign-up.
Pre sign-up PreSignUp_AdminCreateUser Pre sign-up when an admin creates a new user.
Pre sign-up PreSignUp_ExternalProvider Pre sign-up for external identity providers.
Post confirmation PostConfirmation_ConfirmSignUp Post sign-up confirmation.
Post confirmation PostConfirmation_ConfirmForgotPassword Post Forgot Password confirmation.
Pre authentication PreAuthentication_Authentication Pre authentication.
Post authentication PostAuthentication_Authentication Post authentication.

Custom authentication challenge triggers

Trigger triggerSource value Event
Define auth challenge DefineAuthChallenge_Authentication Define Auth Challenge.
Create auth challenge CreateAuthChallenge_Authentication Create Auth Challenge.
Verify auth challenge VerifyAuthChallengeResponse_Authentication Verify Auth Challenge Response.

Pre token generation triggers

Trigger triggerSource value Event
Pre token generation TokenGeneration_HostedAuth Amazon Cognito authenticates the user from your managed login sign-in page.
Pre token generation TokenGeneration_Authentication User authentication or token refresh complete.
Pre token generation TokenGeneration_NewPasswordChallenge Admin creates the user. Amazon Cognito invokes this when the user must change a temporary password.
Pre token generation TokenGeneration_AuthenticateDevice End of the authentication of a user device.
Pre token generation TokenGeneration_RefreshTokens User tries to refresh the identity and access tokens.

Migrate user triggers

Trigger triggerSource value Event
User migration UserMigration_Authentication User migration at the time of sign-in.
User migration UserMigration_ForgotPassword User migration during the forgot-password flow.

Custom message triggers

Trigger triggerSource value Event
Custom message CustomMessage_SignUp Custom message when a user signs up in your user pool.
Custom message CustomMessage_AdminCreateUser Custom message when you create a user as an administrator and Amazon Cognito sends them a temporary password.
Custom message CustomMessage_ResendCode Custom message when your existing user requests a new confirmation code.
Custom message CustomMessage_ForgotPassword Custom message when your user requests a password reset.
Custom message CustomMessage_UpdateUserAttribute Custom message when a user changes their email address or phone number and Amazon Cognito sends a verification code.
Custom message CustomMessage_VerifyUserAttribute Custom message when a user adds an email address or phone number and Amazon Cognito sends a verification code.
Custom message CustomMessage_Authentication Custom message when a user who has configured SMS MFA signs in.

Custom sender triggers

Trigger triggerSource value Event
Custom sender CustomEmailSender_SignUp CustomSmsSender_SignUp When a user signs up in your user pool.
Custom sender CustomEmailSender_AdminCreateUser CustomSmsSender_AdminCreateUser When you create a user as an administrator and Amazon Cognito sends them a temporary password.
Custom sender CustomEmailSender_ForgotPassword CustomSmsSender_ForgotPassword When your user requests a password reset.
Custom sender CustomEmailSender_UpdateUserAttribute CustomSmsSender_UpdateUserAttribute When a user changes their email address or phone number and Amazon Cognito sends a verification code.
Custom sender CustomEmailSender_VerifyUserAttribute CustomSmsSender_VerifyUserAttribute When a user adds an email address or phone number and Amazon Cognito sends a verification code.
Custom sender CustomEmailSender_Authentication CustomSmsSender_Authentication When a user who has configured SMS or email MFA or OTP signs in.
Custom sender CustomEmailSender_AccountTakeOverNotification When your threat protection settings take an automated action against a user's sign-in attempt and the action for the risk level includes a notification.