I want to build an authentication workflow with Amazon Cognito APIs to pass client metadata to AWS Lambda triggers.
Resolution
When you call the InitiateAuth API with the ClientMetadata parameter to initiate user authentication in Amazon Cognito, ClientMetadata is passed to only these Lambda triggers:
In comparison, you must call the RespondToAuthChallenge API to include ClientMetadata in these Lambda triggers:
Include the ClientMetadata parameter in the RespondToAuthChallenge API call to respond to any of these authentication challenges:
- Time-based one-time password (TOTP) multi-factor authentication (MFA)
- Short Message Service (SMS) for MFA
- Device Secure Remote Password (SRP)
- Custom authentication challenges
Additionally, the ClientMetadata parameter enhances custom workflows for Lambda function user pool triggers.
Example RespondToAuthChallenge API call with the ClientMetadata parameter
In this example, an Amazon Cognito user pool is configured with an app client. A post authentication Lambda trigger is associated with the user pool.
The Lambda function named lambda_handler prints the event it receives:
import json
def lambda_handler(event, context):
# TODO implement
print(event)
return event
Important: Use logging carefully in production system to avoid exposing any secure data or secrets in Amazon CloudWatch.
A test user is created in the user pool. Then, SMS for MFA is configured.
The example InitiateAuth API call request initiates user sign in:
aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --auth-parameters USERNAME=test,PASSWORD=Password@123 --client-id 1abcd2efgh34ij5klmnopq456r
The example InitiateAuth API call response:
{
"ChallengeName": "SMS_MFA",
"Session": "1AbcDEfgXXXXX",
"ChallengeParameters": {
"CODE_DELIVERY_DELIVERY_MEDIUM": "SMS",
"CODE_DELIVERY_DESTINATION": "+********1234",
"USER_ID_FOR_SRP": "test"
}
}
The example RespondToAuthChallenge API call request submits MFA code and the ClientMetadata parameter includes any additional information to pass:
aws cognito-idp respond-to-auth-challenge --client-id 9zyxw8vuts76rq5ponmlkj432i --challenge-name SMS_MFA --session "9ZyxWVutXXXXX" --challenge-responses USERNAME=test,SMS_MFA_CODE=654321 --client-metadata KeyName1='string',KeyName2='string'
The example RespondToAuthChallenge API call response:
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "abXXXX",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"RefreshToken": "abXX",
"IdToken": "abXXX"
}
}
After a user successfully authenticates and receives tokens from Amazon Cognito, the post authentication Lambda trigger is invoked.
Find the post authentication Lambda trigger results under log events in the CloudWatch console. Look for the ClientMetadata parameter details in the event body.
Related information
Custom authentication challenge Lambda triggers
Customizing user pool workflows with Lambda triggers