Search code examples
amazon-web-servicesaws-lambdaamazon-cognito

Retrieving cognito user ID in Lambda


I'm writing a Lambda function for a pre-signup trigger on my Cognito pool.

I want to copy the user details to MongoDB when a user signs up.

Therefore, I need access to context.authorizer.claims.sub, the user's Cognito ID.

So far, I've made an Authorizer:

enter image description here

And an ANY method.

After reading this doc, it looks like I need to add context.authorizer.claims.sub in a body mapping template.

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html

However, there seems to be no option on integration request to add a body mapping template

enter image description here

There might be a better way to access the user's Cognito ID, but this seems like it should work.

EDIT

My Lambda config

enter image description here

console.log(context)

2021-05-13T13:02:56.188Z    75c67d1e-0f2e-49c5-be2f-d19affb2dd2b    INFO    {
  callbackWaitsForEmptyEventLoop: [Getter/Setter],
  succeed: [Function (anonymous)],
  fail: [Function (anonymous)],
  done: [Function (anonymous)],
  functionVersion: '$LATEST',
  functionName: 'AuthUtils',
  memoryLimitInMB: '128',
  logGroupName: '/aws/lambda/AuthUtils',
  logStreamName: '2021/05/13/[$LATEST]920d08ed47584c16abd89ffd5c6c12da',
  clientContext: undefined,
  identity: undefined,
  invokedFunctionArn: 'arn:aws:lambda:eu-west-2:022228979186:function:AuthUtils',
  awsRequestId: '75c67d1e-0f2e-49c5-be2f-d19affb2dd2b',
  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis]
}

Solution

  • You can't add integration request mapping to a lambda proxy integration. You can access the request context as event.requestContext in your handler.

    The sub value can be accessed as event.requestContext.authorizer.claims.sub