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

如何通过DynamoDB触发器获取Cognito用户属性生成账单?

Got it, let's break this down. You've got a DynamoDB record tied to a Cognito Identity ID, and you need to pull the user's name/email from the Cognito User Pool to generate a bill via a DynamoDB trigger. Here's how to do it, with two approaches depending on whether you can modify your existing write logic:

最优方案:在DynamoDB中存储User Pool Sub(推荐)

Since you're already using ${cognito-identity.amazonaws.com:sub} as a condition when writing to DynamoDB, you have access to the User Pool user's unique sub value at write time. The simplest and most efficient approach is to add this sub as an attribute (e.g., userPoolSub) to your DynamoDB item.

Once that's in place, your Lambda trigger can directly use this sub to fetch the user's attributes from the User Pool:

Step 1: Update your write logic

When saving the DynamoDB item, include the userPoolSub attribute with the value of ${cognito-identity.amazonaws.com:sub}.

Step 2: Lambda Trigger Code (Node.js example)

const AWS = require('aws-sdk');
const cognitoISP = new AWS.CognitoIdentityServiceProvider({ region: 'us-east-1' });

exports.handler = async (event) => {
  // Extract the new DynamoDB record
  const newItem = event.Records[0].dynamodb.NewImage;
  const userPoolSub = newItem.userPoolSub.S; // Adjust based on your attribute type
  const userPoolId = 'us-east-1_XXXXXX'; // Replace with your User Pool ID

  try {
    // Fetch full user details from the User Pool
    const userResponse = await cognitoISP.adminGetUser({
      UserPoolId: userPoolId,
      Username: userPoolSub // User Pool accepts `sub` as a valid Username parameter
    }).promise();

    // Map attributes to a readable object
    const userAttributes = userResponse.UserAttributes.reduce((attrs, attr) => {
      attrs[attr.Name] = attr.Value;
      return attrs;
    }, {});

    // Extract the data you need for billing
    const fullName = userAttributes.name || `${userAttributes.given_name} ${userAttributes.family_name}`;
    const email = userAttributes.email;

    // Add your bill generation logic here
    console.log(`Generating bill for ${fullName} (${email})`);

    return { statusCode: 200, body: 'Bill generation initiated successfully' };
  } catch (error) {
    console.error('Failed to fetch user data or generate bill:', error);
    throw error;
  }
};

Step 3: IAM Permissions for Lambda

Make sure your Lambda's execution role has permission to call cognito-idp:AdminGetUser. Add this policy to the role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "cognito-idp:AdminGetUser",
      "Resource": "arn:aws:cognito-idp:us-east-1:YOUR_ACCOUNT_ID:userpool/YOUR_USER_POOL_ID"
    }
  ]
}

备选方案:从Identity ID反向查找User Pool用户

If you can't modify the existing DynamoDB write logic, you can use the Identity ID to look up the associated User Pool user. This is less efficient (extra API call) but works:

Lambda Trigger Code (Node.js example)

const AWS = require('aws-sdk');
const cognitoIdentity = new AWS.CognitoIdentity({ region: 'us-east-1' });
const cognitoISP = new AWS.CognitoIdentityServiceProvider({ region: 'us-east-1' });

exports.handler = async (event) => {
  const newItem = event.Records[0].dynamodb.NewImage;
  const identityId = newItem.identityId.S; // Your existing Identity ID attribute
  const identityPoolId = 'us-east-1:YYYYYY-XXXX-XXXX-XXXX-XXXXXXXXXXXX'; // Replace with your Identity Pool ID

  try {
    // Fetch the identity's linked login providers
    const identityResponse = await cognitoIdentity.getId({
      IdentityPoolId: identityPoolId,
      IdentityId: identityId
    }).promise();

    // Find the Cognito User Pool login entry
    const userPoolLoginKey = Object.keys(identityResponse.Logins).find(key => 
      key.startsWith('cognito-idp.')
    );

    if (!userPoolLoginKey) {
      throw new Error('No Cognito User Pool linked to this identity');
    }

    // Extract User Pool ID and user's sub from the login data
    const userPoolId = userPoolLoginKey.split('/')[1];
    const userPoolSub = identityResponse.Logins[userPoolLoginKey];

    // Fetch user attributes (same as the optimal approach)
    const userResponse = await cognitoISP.adminGetUser({
      UserPoolId: userPoolId,
      Username: userPoolSub
    }).promise();

    // Extract attributes and generate bill...
    return { statusCode: 200, body: 'Bill generation initiated successfully' };
  } catch (error) {
    console.error('Failed to fetch user data:', error);
    throw error;
  }
};

Additional IAM Permissions

For this approach, your Lambda role also needs permission for cognito-identity:GetId:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "cognito-identity:GetId",
      "Resource": "arn:aws:cognito-identity:us-east-1:YOUR_ACCOUNT_ID:identitypool/YOUR_IDENTITY_POOL_ID"
    },
    {
      "Effect": "Allow",
      "Action": "cognito-idp:AdminGetUser",
      "Resource": "arn:aws:cognito-idp:us-east-1:YOUR_ACCOUNT_ID:userpool/YOUR_USER_POOL_ID"
    }
  ]
}

内容的提问来源于stack exchange,提问作者Lucas Paim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:32:21