Is it possible to modify AWS Cognito user attributes in the Lambda triggers

altus picture altus · Jan 28, 2018 · Viewed 13.8k times · Source

Having a look at the AWS documentation,

https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-pre-signup

you have the following paramaters available in the Pre Sign-up Lambda fuction:

"request": {
  "userAttributes": {
    "string": "string",
    ....
},
"validationData": {<validation data as key-value (String, String) pairs, from the client>}

is there a way to modify or add additional userAttributes the the event object?

for example:

// Modify an existing username...
event.request.userAttributes.name.ucfirst();

// Add an additional attribute...
event.request.userAttributes.nickname = "ANY_NAME";


callback(null, event);

Answer

Khoi picture Khoi · Mar 17, 2018

Yes, there's absolutely a way! You need to use AWS javascript SDK in your Lambda handler:

const AWS = require('aws-sdk');
AWS.config.update({region: 'ap-southeast-1'});

const cognitoidentityserviceprovider =
  new AWS.CognitoIdentityServiceProvider({
    apiVersion: '2016-04-18'
  });
cognitoidentityserviceprovider.adminUpdateUserAttributes(
  {
    UserAttributes: [
      {
        Name: 'YOUR_USER_ATTRIBUTE_NAME',
        Value: 'YOUR_USER_ATTRIBUTE_VALUE'
      }
    ],
    UserPoolId: event.userPoolId,
    Username: event.userName
  },
  function(err, data) {
    ...
  }
);

Make sure to give your Lambda function the right policies (i.e. allows "cognito-idp:AdminUpdateUserAttributes" action) and the user pool has the attribute defined.