能否通过Cognito完成用户注册并同步创建DynamoDB用户档案?
Got it, let's break down how to solve this correctly—you're right that pre sign-up is risky, but you might have missed that Cognito has a post confirmation trigger that's perfect for this scenario. Here's a step-by-step approach:
Key Clarification: Use Post Confirmation, Not Post Sign-Up
First, let's clear up the trigger confusion:
Pre Sign-upruns before Cognito finalizes user creation, so using it to write to DynamoDB is dangerous (registration could still fail later, leaving orphaned records).Post Confirmationis the right choice—it triggers only after the user has successfully completed registration (whether they verified their email/phone or your user pool is set to auto-confirm accounts). This guarantees the registration process was successful before you create the DynamoDB profile.
Step 1: Configure the Post Confirmation Trigger in Cognito
- Go to your Cognito User Pool in the AWS Console.
- Navigate to the Triggers tab.
- Under the
Post confirmationdropdown, select the Lambda function you want to use (or create a new one directly from here).
Step 2: Write the Lambda Function to Create DynamoDB Profiles
Your Lambda will receive a Cognito event containing the user's attributes (including sub and any custom attributes you collected during registration, like name or website). Here's a Python example using boto3:
import boto3 import json # Initialize DynamoDB resource dynamodb = boto3.resource('dynamodb') user_profiles_table = dynamodb.Table('YourUserProfilesTableName') def lambda_handler(event, context): # Extract user data from the Cognito event user_attributes = event['request']['userAttributes'] user_sub = user_attributes['sub'] user_name = user_attributes.get('name', '') # Fallback to empty string if not provided user_website = user_attributes.get('website', '') created_timestamp = user_attributes['created'] # Write to DynamoDB try: user_profiles_table.put_item( Item={ 'sub': user_sub, 'name': user_name, 'website': user_website, 'created_at': created_timestamp } ) print(f"Successfully created profile for user {user_sub}") except Exception as e: print(f"Error creating user profile: {str(e)}") # Optional: Add error handling (e.g., send an alert, retry logic) # Return the event to Cognito (required for trigger completion) return event
Notes for the Lambda:
- Make sure the attributes you're accessing (like
nameorwebsite) are enabled in your Cognito User Pool's Attributes settings (under "App client settings" or "Attributes" tab). - If you're using JavaScript, the logic is similar—use the AWS SDK for JavaScript v3 to interact with DynamoDB.
Step 3: Set Up Permissions
- Lambda Execution Role: Add a policy that allows
dynamodb:PutItemon your target DynamoDB table. Example policy snippet:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "dynamodb:PutItem", "Resource": "arn:aws:dynamodb:us-east-1:YOUR_ACCOUNT_ID:table/YourUserProfilesTableName" } ] } - Cognito Permission: When you link the Lambda to the Cognito trigger via the console, AWS automatically adds a permission for Cognito to invoke your Lambda. If you set this up manually, you'll need to add a
lambda:InvokeFunctionpermission for your Cognito user pool.
Step 4: Handle Auto-Confirm Scenarios
If your user pool is configured to auto-confirm users (no email/phone verification required), the Post Confirmation trigger still fires immediately after user creation—so your DynamoDB profile will be created right away without any extra steps.
This approach ensures you only create a user profile when registration is fully successful, avoiding the risk of orphaned records from the pre sign-up trigger.
内容的提问来源于stack exchange,提问作者Arsenii Fomin

