Writing Cognito user info to DynamoDB through a post-confirmation lambda function?

Viewed 1880

I'm having trouble implementing a post-confirmation lambda function in which I take the user submitted credentials from the sign-up process and write those to a 'Users' DynamoDB table. The specific entries that I'm trying to write to the table are - user name - email - actual name

In order to distinguish users from one another I need the primary key to be the 'sub' value since users can change their usernames and that could cause problems in the future.

The main points of confusion I'm having are the following

1) What roles should I begin my Lambda function with?

When creating a lambda function I need to give it a starting role and I'm not really sure what starter template I should use. I know I'm going to need DynamoDB write access but I don't see a template for that.

2) How do I access the individual fields of the Cognito user?

As far as I'm aware these values should be stored in the 'event' parameter of the handler function, but I can't find any documentation or sample events that show how to access the individual fields for things like 'sub', 'email', etc.

1 Answers

1) Your Lambda Role

  • Create your Lambda function, rather than use a template, choose to create a new role and give it a name (lets say MyLambdaRole).
  • Go into IAM, go to the Roles menu option and find the MyLambdaRole role. Attach the following policy: AmazonDynamoDBFullAccess

Note that the Lambda will already have CloudWatch access by default. The AmazonDynamoDBFullAccess has more permissions than you strictly need but its not unreasonable. If you did want finer grained permission I would at least get it working with AmazonDynamoDBFullAccess and go from there. Also note you shouldn't need any Cognito permissions at all, as all you will be doing is parsing the data sent to you by Cognito.

Make sure you import the relevant DynamoDB library in your script.

For example:

exports.handler = (event, context, callback) => {

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});

// Create the DynamoDB service object
ddb = new AWS.DynamoDB({apiVersion: '2012-10-08'});

};

2) Accessing the individual Cognito user data

Assuming you are using NodeJs, like this:

event.request.userAttributes.email

More details here

One final thing, you don't need to assign a trigger to the Lambda function. All you need to do is go into Cognito, and assign the Lambda function in the triggers section. That way Cognito calls the Lambda directly - Lambda doesn't need to listen out for any special events.

Related