Customizing User Pool Workflows with Lambda Triggers
Introduction
Amazon Cognito integrates with AWS Lambda to customize the authentication behavior of user pools. Lambda triggers allow you to modify authentication flows, interact with external systems, and update AWS resources.
Lambda functions receive JSON events with user information, enabling actions like user migration, custom messaging, and token modification. For example, we can prevent sign-ins, customize authentication challenges, or enrich user attributes from external sources. Cognito pauses its default workflow, sends an event to your function, and expects a response to continue the process.
Ramp-up
Getting started with Amazon Cognito triggers:
-
Trigger Lifecycle in Cognito
-
User signs up → Pre Sign-up Trigger
(Validate or modify user attributes before creating an account) -
User confirms sign-up → Post Confirmation Trigger
(Send a welcome email or store user data in a database) -
User logs in → Pre Authentication Trigger
(Apply custom authentication rules) -
User successfully logs in → Post Authentication Trigger
(Log sign-ins or enable MFA dynamically) -
User requests a token → Pre Token Generation Trigger
(Modify the ID/Access token with custom claims) -
User forgets password → Custom Message Trigger
(Send custom SMS/email messages)
-
-
Use Cases
-
Authentication & User Lifecycle Triggers
Trigger Name Execution Time Use Cases Pre Sign-up Before creating a user Validate email, check custom attributes, prevent bot registrations. Post Confirmation After successful sign-up Send a welcome email, store user data in DynamoDB. Pre Authentication Before user logs in Block unverified users, check IP for security Post Authentication After successful login Track login history, send login notifications. Migrate User During login (if user doesn’t exist) Migrate users from an external authentication system. -
Multi-Factor Authentication & Custom Challenges
Trigger Name Execution Time Use Cases Define Auth Challenge After password entry Implement custom MFA, like SMS OTP or security questions. Create Auth Challenge During authentication Generate an OTP for verification. Verify Auth Challenge After challenge response Validate the OTP provided by the user. -
Token Modification & Security
Trigger Name Execution Time Use Cases Pre Token Generation Before token is issued Add custom claims (roles, permissions) to ID/Access tokens Custom Message Before sending an email/SMS Personalize verification/reset emails. Custom Sender Before sending email/SMS Use third-party email providers (SendGrid, Mailgun).
-
-
How to use Cognito Triggers
-
Write an AWS Lambda function using Node.js, Python, or Java.
-
Deploy it in AWS Lambda.
-
Associate it with a Cognito User Pool in the AWS Console or CLI.
-
-
Best Practices
-
Optimize for performance: Cognito waits for the Lambda to complete before proceeding. Avoid long processing times to prevent login delays.
-
Use AWS CloudWatch Logs: Track errors and debug efficiently.
-
Use minimal permissions: Assign the least privilege to the Lambda function.
-
Handle errors properly: A failed trigger can block authentication.
-
Avoid infinite loops: Triggers like Post Authentication should not invoke another authentication request.
-
Trigger Categories
-
Sign-up
These triggers are used during the sign-up process.
a. Pre sign-up lambda trigger
Customizes the sign-up process by enabling security checks, governance policies, or third-party user linking, custom analysis and recording of new users. It runs before a new user (local or federated) is signed up, allowing you to analyze, modify, or deny the request.
Request Parameters:
-
userAttributes: Key-value pairs representing user attributes.
Example:
{ "Name": "email", "Value": "example@email.com" },{"Name": "username", "Value": "example"} -
validationData: Temporary key-value pairs passed during user creation, not stored as attributes.
Example:
{ "invitationCode": "ABC123" }, { "age": "21" },{ "country": "USA" } -
clientMetadata: Custom key-value pairs sent as additional input to the Lambda function.
Example:
{ "signupSource": "mobile-app"}, {"userRole": "vendor"}, {"referrer": "user_12345" }
Response Parameters:
-
autoConfirmUser: Automatically confirms the user when set to `true`.
-
autoVerifyEmail: Marks the user’s email as verified if set to `true`, requiring a valid email. Performs verification of email.
-
autoVerifyPhone: Marks the user’s phone number as verified if set to `true`, requiring a valid phone number. Performs verification of phone number.
b. Post confirmation lambda trigger
This is triggered after a user confirms sign-up, allowing custom messages, API calls, or attribute updates. It applies only to self-signed-up users, not admin-created accounts.
Request Parameters:-
userAttributes: Key-value pairs representing user details.
Example:
{ "email": "user@example.com", "given_name": "John" } -
clientMetadata: Custom key-value pairs sent as additional input to the Lambda function.
Example:
{ "signupSource": "mobile-app", "referrer": "user_12345" }
c. Migrate user lambda trigger
This is triggered during sign-in or password reset if a user doesn’t exist, allowing migration from an external directory before creating the user in the pool.Request Parameters:
-
userName: The username that the user enters at sign-in.
Example:
"userName": "johndoe@example.com" } -
password: The password that the user enters at sign-in. Not sent in the forgot-password flow.
Example:
{ "password": "SecureP@ssw0rd!" } -
validationData: Key-value pairs containing additional validation data for the sign-in request.
Example:
{ "validationData": { "source": "web", "device": "mobile" }} -
clientMetadata: Custom key-value pairs sent as additional input to the Lambda function.
Example:
{ "clientMetadata": { "referrer": "promo_campaign" } }
Response Parameters:
-
userAttributes: Required key-value pairs that define the user profile attributes in the Cognito user pool. Custom attributes must use the custom: prefix.
-
finalUserStatus: Defines the user’s status after migration. Set to CONFIRMED to allow immediate sign-in or RESET_REQUIRED to force a password reset.
-
messageAction: Set to SUPPRESS to prevent Amazon Cognito from sending a welcome message.
-
desiredDeliveryMediums: Defines the method for sending the welcome message (EMAIL or SMS).
-
forceAliasCreation: If true, reassigns an existing alias (email or phone) from another user to the new user.
-
enableSMSMFA: If true, requires the user to complete SMS-based MFA during sign-in.
-
-
Authentication
a. Pre authentication lambda trigger
Amazon Cognito invokes this trigger when a user attempts to sign in so that you can create custom validation that performs preparatory actions. For example, you can deny the authentication request or record session data to an external system.
This Lambda trigger doesn’t activate when a user doesn’t exist, or already has an existing session in your user pool.Request Parameters:
-
userAttributes: One or more name-value pairs that represent user attributes.
Example:
"userAttributes": { "email": "user@example.com", "email_verified": "true" } -
userNotFound: When you set PreventUserExistenceErrors to ENABLED for your user pool client, Amazon Cognito populates this Boolean.
Example:
"userNotFound": false
Response:
Amazon Cognito does not expect any additional return information in the response. Your function can return an error to reject the sign-in attempt, or use API operations to query and modify your resources.
b. Post authentication lambda trigger
The post authentication trigger doesn’t change the authentication flow for a user. Amazon Cognito invokes this Lambda after authentication is complete, before a user has received tokens. Add a post authentication trigger when you want to add custom post-processing of
authentication events, for example logging or user profile adjustments that will be reflected on the next sign-in.Request Parameters:
-
newDeviceUsed: This flag indicates if the user has signed in on a new device. Amazon Cognito only sets this flag if the remembered devices value of the user pool is Always or User Opt-In.
Example:
"newDeviceUsed": boolean -
userAttributes: One or more name-value pairs that represent user attributes.
Example:
"userAttributes": { "email": "user@example.com", "email_verified": "true" } -
clientMetadata: One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the post authentication 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.
Example:
"clientMetadata": {"string": "string"}
Response:
Amazon Cognito doesn’t expect any additional return information in the response. Your function can use API operations to query and modify your resources, or record event metadata to an external system.
c. Pre token generation lambda trigger
Your user pool can deliver different versions of a pre token generation trigger event to your Lambda function. A V1_0 trigger delivers the parameters for modification of ID tokens. A V2_0 trigger delivers parameters for the following:- The functions of a V1_0 trigger.
- The ability to customize access tokens.
- The ability to pass complex datatypes to ID and access token claim values:
- String
- Number
- Boolean
- Array of strings, numbers, booleans, or a combination of any of these
- JSON
This Lambda trigger can add, remove, and modify some claims in identity and access tokens before Amazon Cognito issues them to your app. To use this feature, associate a Lambda function from the Amazon Cognito user pools console or update your user pool LambdaConfig through the AWS Command Line Interface (AWS CLI).
The uses of the pre token generation Lambda trigger with an ID token include the following:
- Make a change at runtime to the IAM role that your user requests from an identity pool.
- Add user attributes from an external source.
- Add or replace existing user attribute values.
- Suppress disclosure of user attributes that, because of your user’s authorized scopes and the read access to attributes that you granted to your app client, would otherwise be passed to your app.
The uses of the pre token generation Lambda trigger with an ID token include the following:
- Make a change at runtime to the IAM role that your user requests from an identity pool.
- Add user attributes from an external source.
- Add or replace existing user attribute values.
- Suppress disclosure of user attributes that, because of your user’s authorized scopes and the read access to attributes that you granted to your app client, would otherwise be passed to your app.
-
-
Custom authentication
a. Define auth challenge lambda trigger
Maintains the challenge sequence in a custom authentication flow. It declares success or failure of the challenge sequence, and sets the next challenge if the sequence isn’t yet complete.Request Parameters:
-
userAttributes: Key-value pairs representing the user’s attributes.
Example:
{ "userAttributes": { "email": "user@example.com", "phone_number": "+1234567890" } } -
userNotFound: A boolean indicating whether the provided user credentials match an existing user when PreventUserExistenceErrors is enabled.
Example:
{ "userNotFound": true } -
session: An array containing previous authentication challenge attempts.
Example:
{ "session": [ { "challengeName": "PASSWORD_VERIFIER", "challengeResult": true }] } -
challengeName: The type of authentication challenge issued by Cognito (e.g., CUSTOM_CHALLENGE, PASSWORD_VERIFIER, SMS_MFA).
Example:
{ "challengeResult": true } -
challengeResult: Boolean indicating whether the user successfully completed the previous challenge.
Example:
{ "challengeResult": true } -
challengeMetadata: Custom identifier for a CUSTOM_CHALLENGE.
Example:
{ "challengeMetadata": "captcha_verification" } -
clientMetadata: Key-value pairs sent as custom input to the Lambda function.
Example:
{ "clientMetadata": { "loginSource": "mobile-app" } }
Response Parameters:
-
challengeName: Specifies the next challenge in the authentication process (e.g., SMS_MFA, CUSTOM_CHALLENGE).
-
issueTokens: Set to true if the user has successfully completed authentication and should receive tokens.
-
failAuthentication: Set to true to terminate the authentication process if the user fails validation.
b. Create Auth challenge Lambda trigger
Processes challenges defined by the define auth challenge trigger. It returns publicChallengeParameters for the user and privateChallengeParameters for verification, managing the challenge contents.
Request Parameters:-
userAttributes: Key-value pairs representing the user’s attributes.
Example:
{ "userAttributes": { "email": "user@example.com", "phone_number": "+1234567890" } } -
userNotFound: A boolean indicating whether the user exists when PreventUserExistenceErrors is enabled.
Example:
{ "userNotFound": true } -
challengeName: The name of the new authentication challenge.
Example:
{ "challengeName": "CUSTOM_CHALLENGE" } -
session: An array containing previous authentication challenge attempts.
Example:
{ "session": [ { "challengeName": "PASSWORD_VERIFIER", "challengeResult": true }] } -
challengeName: Custom identifier for a CUSTOM_CHALLENGE.
Example:
{ "challengeMetadata": "captcha_verification" } -
challengeResult: Boolean indicating whether the user successfully completed the previous challenge.
Example:
{ "challengeResult": true } -
challengeMetadata: Custom identifier for a CUSTOM_CHALLENGE.
Example:
{ "challengeMetadata": "captcha_verification" } -
clientMetadata: Key-value pairs sent as custom input to the Lambda function.
Example:
{ "clientMetadata": { "authSource": "mobile-app" } }
Response Parameters:
-
publicChallengeParameters: Key-value pairs sent to the client app to present the challenge to the user.
-
privateChallengeParameters: Key-value pairs used internally to validate the user’s response.
-
challengeMetadata: A custom identifier for the challenge, used for tracking or validation.
c. Verify auth challenge response Lambda trigger
Validates the user’s response against a known answer, determining if it’s correct. If answerCorrect is true, authentication proceeds.
Request Parameters:-
userAttributes: Key-value pairs representing the user’s attributes.
Example:
{ "userAttributes": { "email": "user@example.com", "phone_number": "+1234567890" } } -
userNotFound: A boolean indicating whether the user exists when PreventUserExistenceErrors is enabled.
Example:
{ "userNotFound": true } -
privateChallengeParameters: Key-value pairs from the Create Auth Challenge trigger, used to validate the user’s response.
Example:
{ "privateChallengeParameters": { "correctAnswer": "X7Y9Z" } } -
challengeAnswer: The answer provided by the user in response to the challenge.
Example:
{ "challengeAnswer": "X7Y9Z" } -
clientMetadata: Custom key-value pairs sent as input to the Lambda function for the Verify Auth Challenge trigger.
Example:
{ "clientMetadata": { "authSource": "mobile-app" } }
Response Parameters:
- answerCorrect: Boolean indicating whether the user’s response to the challenge is correct.
-
-
Messaging
a. Custom message Lambda trigger
Use a custom message trigger in your Cognito user pool to format email and SMS messages dynamically. This Lambda function modifies message content before sending verification codes or MFA messages. The request includes codeParameter, a placeholder replaced with the actual code before delivery.
Request Parameters:
-
userAttributes: One or more name-value pairs representing user attributes.
-
codeParameter: A string for you to use as the placeholder for the verification code in the custom message.
-
usernameParameter: The user name. Amazon Cognito includes this parameter in requests that result from admin-created users.
-
clientMetadata: One or more key-value pairs that you can provide as custom input to the Lambda function that you specify for the custom message trigger.
Response Parameters:
- smsMessage: The custom SMS message to be sent to your users. Must include the codeParameter value that you received in the request.
- emailMessage: The custom email message to send to your users.
- emailSubject: The subject line for the custom message.
-
Common Used Triggers
-
Authentication Lambda trigger
a. Pre authentication trigger
The Pre-Authentication trigger in AWS Cognito adds an extra security layer before authentication. It allows developers to implement custom security checks, user validations, and access restrictions before allowing a user to log in. By leveraging this trigger, organizations can block unauthorized access, enforce policies, and protect user accounts from potential threats.b. Post authentication trigger
The Post-Authentication trigger in AWS Cognito enhances security and user experience after authentication. It allows developers to implement custom post-login actions, such as tracking login activity, detecting anomalies, enforcing Multi-Factor Authentication (MFA), and updating user session data. By leveraging this trigger, organizations can monitor user sessions, enhance security, and personalize user experiences while ensuring compliance with access policies. -
Custom Authentication
a. Define auth challenge
The Define Auth Challenge trigger in AWS Cognito dynamically determines what authentication challenges to enforce based on user behavior and risk level. It allows developers to implement adaptive authentication, balancing security and user experience. By leveraging this trigger, organizations can enhance account security, prevent unauthorized access, and provide a seamless yet secure login experience.b. Create auth challenge
The Create Auth Challenge trigger in AWS Cognito is responsible for generating and delivering authentication challenges based on security policies. It allows developers to implement custom multi-factor authentication (MFA), CAPTCHA-based protection, security questions, and push notifications to enhance login security. By leveraging this trigger, organizations can create dynamic authentication flows, reduce fraudulent access, and provide seamless yet secure login mechanisms.c. Verify auth challenge response
The Verify Auth Challenge trigger in AWS Cognito is responsible for validating a user’s response to a custom authentication challenge. It ensures that the provided answer matches the expected response, allowing the authentication process to continue if successful. This trigger enables developers to implement custom authentication flows, such as security questions, MFA verifications, and other challenge-based mechanisms. By leveraging this trigger, organizations can enhance security, prevent unauthorized access, and create flexible authentication workflows tailored to their needs.
Code Examples
Define Auth Challenge
/* AWS Lambda function for Define Auth challenge.
This function determines the next authentication challenge in Cognito's flow.
It evaluates the user's session and decides whether to proceed, retry, or fail authentication.
Challenge Flow:
1. If SRP_A (Secure Remote Password) is successful → Move to PASSWORD_VERIFIER.
2. If PASSWORD_VERIFIER is successful → Move to CUSTOM_CHALLENGE (e.g., OTP verification).
3. If CUSTOM_CHALLENGE fails multiple times → Fail authentication.
4. If CUSTOM_CHALLENGE is successful → Issue authentication tokens.
* @param {any} event - The Cognito event object, containing authentication session data.
* @param {any} _context - The Lambda execution context (not used in this function).
* @param {any} callback - The callback function (not explicitly used, as we return `event`).
* @returns {any}- The updated event object with authentication decisions.
* Error Handling:
- If the user fails CUSTOM\_CHALLENGE multiple times, authentication fails.**
- If an unknown challenge state occurs, the user is prompted to retry CUSTOM\_CHALLENGE.**
*/
export const handler = async (event, _context, callback) => {
if (
event.request.session &&
event.request.session.length === 1 &&
event.request.session[0].challengeName === 'SRP_A' &&
event.request.session[0].challengeResult === true
) {
// SRP_A is the first challenge in Cognito's authentication flow.
// If the first challenge is successful, Cognito sets the next challenge as PASSWORD_VERIFIER.
event.response.issueTokens = false; // No tokens issued yet, as further challenges are pending.
event.response.failAuthentication = false; // Authentication has not failed; it moves to the next challenge.
event.response.challengeName = 'PASSWORD_VERIFIER'; // Proceed to the PASSWORD_VERIFIER challenge.
} else if (
event.request.session &&
event.request.session.length === 2 &&
event.request.session[1].challengeName === 'PASSWORD_VERIFIER' &&
event.request.session[1].challengeResult === true
) {
// If the password verification is successful, move to the CUSTOM_CHALLENGE step (e.g., OTP verification).
event.response.issueTokens = false; // No tokens issued yet, as another challenge is required.
event.response.failAuthentication = false; // Authentication has not failed; move to the next challenge.
event.response.challengeName = 'CUSTOM_CHALLENGE'; // Set the next challenge as CUSTOM_CHALLENGE.
} else if (
event.request.session &&
event.request.session.length >= 5 &&
event.request.session.slice(-1)[0].challengeName === 'CUSTOM_CHALLENGE' &&
event.request.session.slice(-1)[0].challengeResult === false
) {
// The user has failed the CUSTOM_CHALLENGE multiple times (n failed attempts in Cognito).
// User must restart the process.
event.response.issueTokens = false; // No tokens issued since authentication has failed.
event.response.failAuthentication = true; // Authentication fails after multiple incorrect attempts.
} else if (
event.request.session &&
event.request.session.slice(-1)[0].challengeName === 'CUSTOM_CHALLENGE'
) {
if (event.request.session.slice(-1)[0].challengeResult === false) {
// The user provided an incorrect response to the CUSTOM_CHALLENGE,
// but they still have attempts remaining. Re-attempt the challenge.
event.response.issueTokens = false;
event.response.failAuthentication = false;
event.response.challengeName = 'CUSTOM_CHALLENGE';
} else {
// The user successfully completed CUSTOM_CHALLENGE, meaning authentication is complete.
// Cognito should now issue tokens.
event.response.issueTokens = true; // Tokens issued since authentication has succeeded.
event.response.failAuthentication = false; // Authentication has succeeded.
}
} else {
// The user has not provided a correct answer yet, so they must retry CUSTOM_CHALLENGE.
// This ensures they are still in the authentication flow.
event.response.issueTokens = false;
event.response.failAuthentication = false;
event.response.challengeName = 'CUSTOM_CHALLENGE';
}
return event;
};
Create Auth Challenge
// AWS Lambda function for Create Auth challenge - generating and validating OTPs in Cognito's custom challenge flow.
// This function determines whether a new OTP should be generated or if an existing OTP
// (from a previous challenge attempt) is still valid. If a new OTP is required, it generates
// one, stores it with an expiration timestamp, and sends it via Twilio SMS.
// OTP Handling Logic:
// - If an OTP exists in the session and is still valid, it is reused.
// - If no OTP exists or the previous OTP has expired, a new OTP is generated.
// - The OTP and expiration timestamp are stored in Cognito's privateChallengeParameters.
// - The OTP is sent to the user's registered phone number via Twilio.
// @param {Object} event - The event object from AWS Cognito, containing user attributes and session data.
// @param {Object} _context - The Lambda execution context (not used in this function).
// @param {Function} callback - The callback function to return the response or an error.
// @returns {void} - The function updates the event object and invokes the callback with the modified event.
// Error Handling:
// - If an error occurs (e.g., failure to generate an OTP or send an SMS), the callback returns an error message.
exports.handler = async (event, _context, callback) => {
let verificationCode;
try {
const eventData = event;
const session = eventData.request.session;
const sessionLength = session.length;
// Extract the last challenge attempt
const lastAttempt = sessionLength > 0 ? session[sessionLength - 1] : null;
const previousVerificationCode = lastAttempt ? lastAttempt.challengeMetadata : null;
let shouldGenerateNewOTP = false;
let otp;
if (previousVerificationCode) {
// If previous OTP exists, check expiration
const [storedOtp, expirationTimestamp] = previousVerificationCode.split('|');
const currentTime = new Date().getTime();
// OTP has expired
if (currentTime > parseInt(expirationTimestamp, 10)) {
shouldGenerateNewOTP = true; // Generate new OTP
}
// OTP is valid
else {
otp = storedOtp; // Reuse existing OTP
}
} else {
shouldGenerateNewOTP = true; // No previous OTP found. Generate a new OTP
}
if (shouldGenerateNewOTP) {
otp = await helper.generateOtp(); // Generate new OTP
const otpIssuedTime = new Date().getTime(); // Current timestamp
const otpExpirationTime = otpIssuedTime + 10 * 60 * 1000; // 10 minutes expiry
verificationCode = `${otp}|${otpExpirationTime}`;
await helper.sendTwilioSMS(
event.request.userAttributes['phone_number'],
{ otp: String(otp) },
process.env.TWILIO_CLIENT,
process.env.LOGIN_SMS_TEMPLATE
);
} else {
verificationCode = previousVerificationCode; // Keep old OTP if still valid
}
// Store the OTP in Cognito's privateChallengeParameters
eventData.response.privateChallengeParameters = { verificationCode };
eventData.response.challengeMetadata = verificationCode;
callback(null, eventData);
} catch (error) {
callback('Something went wrong', event);
}
};
Verify Auth Challenge
// AWS Lambda function for Verify Auth challenge - handling Cognito custom challenge with OTP verification. This is where the verification
// of custom auth challenge takes place.
// This function checks whether a previously issued OTP is still valid.
// - If the OTP has expired, a new one is generated and sent via Twilio SMS.
// - If the OTP is still valid, it is reused.
// - The OTP and its expiration timestamp are stored in Cognito's private challenge parameters.
// @param {Object} event - The event object from AWS Cognito, containing user attributes and session data.
// @param {Object} _context - The Lambda execution context (unused in this function).
// @param {Function} callback - The callback function to return the response or error.
// @returns {void} - Returns the updated event object via callback with the verification code stored.
// Error Handling:
// - If any error occurs, the function calls the callback with an error message.
exports.handler = async (event, _context, callback) => {
let verificationCode;
try {
const eventData = event;
const session = eventData.request.session;
const sessionLength = session.length;
// Extract the last challenge attempt
const lastAttempt = sessionLength > 0 ? session[sessionLength - 1] : null;
const previousVerificationCode = lastAttempt ? lastAttempt.challengeMetadata : null;
let shouldGenerateNewOTP = false;
let otp;
if (previousVerificationCode) {
// If previous OTP exists, check expiration
const [storedOtp, expirationTimestamp] = previousVerificationCode.split('|');
const currentTime = new Date().getTime();
// OTP has expired
if (currentTime > parseInt(expirationTimestamp, 10)) {
shouldGenerateNewOTP = true; // Generating new OTP
}
// OTP is valid
else {
otp = storedOtp; // Reuse existing OTP
}
} else {
shouldGenerateNewOTP = true; // No previous OTP found. New OTP should be generated
}
if (shouldGenerateNewOTP) {
otp = await helper.generateOtp(); // Generate new OTP
const otpIssuedTime = new Date().getTime(); // Current timestamp
const otpExpirationTime = otpIssuedTime + 10 * 60 * 1000; // 10 minutes expiry
verificationCode = `${otp}|${otpExpirationTime}`;
await helper.sendTwilioSMS(
event.request.userAttributes['phone_number'],
{ otp: String(otp) },
process.env.TWILIO_CLIENT,
process.env.LOGIN_SMS_TEMPLATE
);
} else {
verificationCode = previousVerificationCode; // Keep old OTP if still valid
}
// Store the OTP in Cognito's privateChallengeParameters
eventData.response.privateChallengeParameters = { verificationCode };
eventData.response.challengeMetadata = verificationCode;
callback(null, eventData);
} catch (error) {
callback('Something went wrong', event);
}
};
References
-
AWS: Using Lambda triggers Customizing user pool workflows with Lambda triggers
Contributors
This post was created with the contributions of the following individuals. For any doubts or further inquiries, feel free to contact the contributors:
-
Deepak Boniface Cardoza - deepak.cardoza@7edge.com
-
Arpith K - arpith.k@7edge.com
-
Clinton Justin Noronha - clinton.noronha@7edge.com