Custom email sender Lambda trigger - Amazon Cognito

Custom email sender Lambda trigger

Amazon Cognito invokes the custom email sender trigger so that a third-party provider can send email notifications to your users from your AWS Lambda function code. Amazon Cognito sends email message events as requests to a Lambda function. The custom code of your function must then process and deliver the message.

Note

Currently, you can't assign a custom email sender trigger in the Amazon Cognito console. You can assign a trigger with the LambdaConfig parameter in a CreateUserPool or UpdateUserPool API request.

To set up this trigger, perform the following steps:

  1. Create an encryption key in AWS Key Management Service (AWS KMS). Amazon Cognito generates secrets (temporary passwords and authorization codes), then uses this KMS key to encrypt the secrets. You can then use the AWS Encryption SDK in your Lambda function to decrypt the codes and send them to the user in plaintext.

  2. Create a Lambda function that you want to assign as your custom sender trigger. Grant the execution role that you assign to your Lambda function kms:Decrypt permissions for your KMS key.

  3. Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to invoke the Lambda function and to create a grant for your KMS key.

  4. Write Lambda function code that directs your messages to custom delivery methods or third-party providers.

  5. Update the user pool so that it uses a custom sender Lambda trigger.

Important

When you configure a custom email sender or a custom SMS sender function for your user pool, configure a symmetric AWS KMS key for additional security. Amazon Cognito uses your configured KMS key to encrypt codes or temporary passwords. Amazon Cognito sends the base64 encoded ciphertext to your Lambda functions. For more information, see Symmetric KMS keys.

Custom email sender Lambda trigger parameters

These are the parameters that Amazon Cognito passes to this Lambda function along with the event information in the common parameters.

JSON
{ "request": { "type": "customEmailSenderRequestV1", "code": "string", "clientMetadata": { "string": "string", . . . }, "userAttributes": { "string": "string", . . . } }

Custom email sender request parameters

type

The request version. For a custom email sender event, the value of this string is always customEmailSenderRequestV1.

code

The encrypted code that your function can decrypt and send to your user.

clientMetadata

One or more key-value pairs that you can provide as custom input to the custom email sender Lambda function trigger. To pass this data to your Lambda function, you can use the ClientMetadata parameter in the AdminRespondToAuthChallenge and RespondToAuthChallenge API actions. Amazon Cognito doesn't include data from the ClientMetadata parameter in AdminInitiateAuth and InitiateAuth API operations in the request that it passes to the post authentication function.

userAttributes

One or more key-value pairs that represent user attributes.

Custom email sender response parameters

Amazon Cognito doesn't expect any additional return information in the custom email sender response. Your function can use API operations to query and modify your resources, or record event metadata to an external system.

Activating the custom email sender Lambda trigger

To set up a custom email sender trigger that uses custom logic to send email messages for your user pool, activate the trigger as follows. The procedure that follows assigns a custom email trigger, a custom SMS trigger, or both to your user pool. After you add your custom email sender trigger, Amazon Cognito always sends user attributes, including the email address, and the one-time code to your Lambda function when it would have otherwise sent an email message with Amazon Simple Email Service.

Important

Amazon Cognito HTML-escapes reserved characters like < (&lt;) and > (&gt;) in your user's temporary password. These characters might appear in temporary passwords that Amazon Cognito sends to your custom email sender function, but don't appear in temporary verification codes. To send temporary passwords, your Lambda function must unescape these characters after it decrypts the password, and before it sends the message to your user.

  1. Create an encryption key in AWS KMS. This key encrypts temporary passwords and authorization codes that Amazon Cognito generates. You can then decrypt these secrets in the custom sender Lambda function and send them to your user in plaintext.

  2. Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to encrypt codes with the KMS key.

    Apply the following resource-based policy to your KMS key.

    { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": "cognito-idp.amazonaws.com" }, "Action": "kms:CreateGrant", "Resource": "arn:aws:kms:us-west-2:111222333444:key/1example-2222-3333-4444-999example", "Condition": { "StringEquals": { "aws:SourceAccount": "111222333444" }, "ArnLike": { "aws:SourceArn": "arn:aws:cognito-idp:us-west-2:111222333444:userpool/us-east-1_EXAMPLE" } } }] }
  3. Create a Lambda function for the custom sender trigger. Amazon Cognito uses the AWS encryption SDK to encrypt the secrets, temporary passwords and codes that authorize your users' API requests.

    1. Assign an IAM role to your Lambda function that has, at minimum, kms:Decrypt permissions for your KMS key.

  4. Grant Amazon Cognito service principal cognito-idp.amazonaws.com access to invoke the Lambda function.

    The following AWS CLI command grants Amazon Cognito permission to invoke your Lambda function:

    aws lambda add-permission --function-name lambda_arn --statement-id "CognitoLambdaInvokeAccess" --action lambda:InvokeFunction --principal cognito-idp.amazonaws.com
  5. Compose your Lambda function code to send your messages. Amazon Cognito uses AWS Encryption SDK to encrypt secrets before Amazon Cognito sends the secrets to the custom sender Lambda function. In your function, decrypt the secret and process any relevant metadata. Then send the code, your own custom message, and destination phone number to the custom API that delivers your message.

  6. Add the AWS Encryption SDK to your Lambda function. For more information, see AWS Encryption SDK programming languages. To update the Lambda package, complete the following steps.

    1. Export your Lambda function as a .zip file in the AWS Management Console.

    2. Open your function and add the AWS Encryption SDK. For more information and download links, see AWS Encryption SDK programming languages in the AWS Encryption SDK Developer Guide.

    3. Zip your function with your SDK dependencies, and upload the function to Lambda. For more information, see Deploying Lambda functions as .zip file archives in the AWS Lambda Developer Guide.

  7. Update your user pool to add custom sender Lambda triggers. Include a CustomSMSSender or CustomEmailSender parameter in an UpdateUserPool API request. The UpdateUserPool API operation requires all the parameters of your user pool and the parameters that you want to change. If you don't provide all relevant parameters, Amazon Cognito sets the values of any missing parameters to their defaults. As demonstrated in the example that follows, include entries for all Lambda functions that you want to add to or keep in your user pool. For more information, see Updating user pool configuration.

    #Send this parameter in an 'aws cognito-idp update-user-pool' CLI command, including any existing #user pool configurations. --lambda-config "PreSignUp={LambdaVersion=V1_0,LambdaArn=lambda-arn}, \ CustomSMSSender={LambdaVersion=V1_0,LambdaArn=lambda-arn}, \ CustomEmailSender={LambdaVersion=V1_0,LambdaArn=lambda-arn}, \ KMSKeyID=key-id"

To remove a custom sender Lambda trigger with an update-user-pool AWS CLI, omit the CustomSMSSender or CustomEmailSender parameter from --lambda-config, and include all other triggers that you want to use with your user pool.

To remove a custom sender Lambda trigger with an UpdateUserPool API request, omit the CustomSMSSender or CustomEmailSender parameter from the request body that contains the rest of your user pool configuration.

Code example

The following Node.js example processes an email message event in your custom email sender Lambda function. This example assumes your function has two environment variables defined.

KEY_ALIAS

The alias of the KMS key that you want to use to encrypt and decrypt your users' codes.

KEY_ARN

The Amazon Resource Name (ARN) of the KMS key that you want to use to encrypt and decrypt your users' codes.

const AWS = require('aws-sdk'); const b64 = require('base64-js'); const encryptionSdk = require('@aws-crypto/client-node'); //Configure the encryption SDK client with the KMS key from the environment variables. const { encrypt, decrypt } = encryptionSdk.buildClient(encryptionSdk.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT); const generatorKeyId = process.env.KEY_ALIAS; const keyIds = [ process.env.KEY_ARN ]; const keyring = new encryptionSdk.KmsKeyringNode({ generatorKeyId, keyIds }) exports.handler = async (event) => { //Decrypt the secret code using encryption SDK. let plainTextCode; if(event.request.code){ const { plaintext, messageHeader } = await decrypt(keyring, b64.toByteArray(event.request.code)); plainTextCode = plaintext } //PlainTextCode now contains the decrypted secret. if(event.triggerSource == 'CustomEmailSender_SignUp'){ //Send an email message to your user via a custom provider. //Include the temporary password in the message. } else if(event.triggerSource == 'CustomEmailSender_ResendCode'){ } else if(event.triggerSource == 'CustomEmailSender_ForgotPassword'){ } else if(event.triggerSource == 'CustomEmailSender_UpdateUserAttribute'){ } else if(event.triggerSource == 'CustomEmailSender_VerifyUserAttribute'){ } else if(event.triggerSource == 'CustomEmailSender_AdminCreateUser'){ } else if(event.triggerSource == 'CustomEmailSender_AccountTakeOverNotification'){ } return; };

Custom email sender Lambda trigger sources

The following table shows the triggering events for custom email trigger sources in your Lambda code.

TriggerSource value Event
CustomEmailSender_SignUp A user signs up and Amazon Cognito sends a welcome message.
CustomEmailSender_ForgotPassword A user requests a code to reset their password.
CustomEmailSender_ResendCode A user requests a replacement code to reset their password.
CustomEmailSender_UpdateUserAttribute A user updates an email address or phone number attribute and Amazon Cognito sends a code to verify the attribute.
CustomEmailSender_VerifyUserAttribute A user creates a new email address or phone number attribute and Amazon Cognito sends a code to verify the attribute.
CustomEmailSender_AdminCreateUser You create a new user in your user pool and Amazon Cognito sends them a temporary password.
CustomEmailSender_AccountTakeOverNotification Amazon Cognito detects an attempt to take over a user account and sends the user a notification.