User Pool not invoking post confirmation lambda trigger

0

Hello, I'm just testing and pretty new to all of this, but I am using the Cognito Hosted UI for sign in/sign up. I'd like for when my users sign up, them to be added to my UsersTable. When I create a test event in my lambda function and run the below code, the user is added to the table just fine

`

import json
import boto3
import logging

# Set up logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

dynamodb = boto3.resource('dynamodb')
users_table = dynamodb.Table('UsersTable')

def lambda_handler(event, context):
    logger.info("Event received: %s", json.dumps(event))
    
    try:
        # Extract user attributes from the event
        user_id = event['request']['userAttributes']['sub']
        email = event['request']['userAttributes']['email']
        username = event['request']['userAttributes']['username']
        
        logger.info(f"Extracted user_id: {user_id}, email: {email}, username: {username}")
        
        # Add the new user to the DynamoDB table
        users_table.put_item(
            Item={
                'UserID': user_id,
                'Email': email,
                'Username': username,
                'Balance': 0  # Initial balance
            }
        )
        logger.info(f"User {username} added to DynamoDB with initial balance 0")
    
    except Exception as e:
        logger.error(f"Error adding user to DynamoDB: {e}")
        raise e
    
    # Return to Amazon Cognito
    return event

` But, when I add this function as a post confirmation trigger in my user pool and create, and confirm, a new user, nothing happens. It doesn't write to Cloudwatch either even though it should be. The policies currently attached to the lambda function are AmazonCognitoDeveloperAuthenticatedIdentities, AmazonCognitoPowerUser, AmazonDynamoDBFullAccess, AWSLambdaBasicExecutionRole and these two inline policies

{
    "Version": "2012-10-17",
    "Id": "default",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:us-east-1:775528215319:function:AddUserToDynamoDB",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceAccount": "775528215319"
                },
                "ArnLike": {
                    "AWS:SourceArn": "arn:aws:cognito-idp:us-east-1:775528215319:userpool/us-east-1_Nocl4lqKD"
                }
            }
        }
    ]
}
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

I know those are probably more permissions than necessary, but I am once again jut testing/learning things. Is there anything I'm missing that I should be adding?

1 Answer
0
Accepted Answer

You need to allow Cognito service to invoke the Lambda function by updating the Lambda function's resource based policy (not to be confused with the Lambda execution role policies which determine which API calls the Lambda is allowed to perform).

In AWS management console navigate to your lambda function -> Configuration -> Permissions -> Resource-based policy statements -> Add permissions.

In the Edit policy statement dialog:

  • Select AWS service radio button
  • Service: Other
  • Statement ID: lambda-allow-cognito (doesn't really matter)
  • Principal: cognito-idp.amazonaws.com
  • Source ARN: <your user pool ARN>
  • Action: lambda:InvokeFunction
  • Save
profile pictureAWS
EXPERT
answered a month ago
  • Thank you so much, you're an absolute life saver!!!