You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过Cognito完成用户注册并同步创建DynamoDB用户档案?

Solution for Auto-Creating DynamoDB User Profiles After Cognito Registration

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-up runs before Cognito finalizes user creation, so using it to write to DynamoDB is dangerous (registration could still fail later, leaving orphaned records).
  • Post Confirmation is 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

  1. Go to your Cognito User Pool in the AWS Console.
  2. Navigate to the Triggers tab.
  3. Under the Post confirmation dropdown, 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 name or website) 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:PutItem on 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:InvokeFunction permission 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:37:48