3
votes

Im building a serverless backend using the following AWS technologies:

  • AWS api_gateway
  • AWS cognito
  • AWS lambda

In api_gateway I have created a Cognito User Pool authorizer and Im using this authorizer for all requests to the backend.

Everything works: When a user makes a request with an invalid JWT token, the server respons accordingly. A valid JWT token executes the requested Lambda function.

Problem: I'm unable to retrieve identity information, such as accessKey, accountId, cognitoIdentityId and so forth. All these variables are null when I access them via the context object in the lambda function

Question: What do I need to do in order to get the identity variables?

2
I did look at the question and answers, but nothings seems to work for me. - Vingtoft
I am wondering if you are missing the body mapping as described here. aws.amazon.com/blogs/mobile/… - JamesKn
The example you have linked uses a custom authorizer. I wonder if its possible to get the context of the signed in user using Cognito User Pool authorizer. I guess its a pretty common use case, so Im confused why it has to be so complicated! Thanks a lot, any help is much appreciated! - Vingtoft

2 Answers

4
votes

The context object in the Lambda function contains the context from Lambda's perspective. The Lambda function is running with the identity of it's execution role, thus its context won't contain the identity attributes from the Cognito user pool.

API Gateway exposes the Cognito user pool identity information via $context.authorizer.claims variable within API Gateway. To access this information from within your Lambda function, you must modify your body mapping template in API Gateway to pass the desired data from $context.authorizer.claims to your Lambda function via the request body. You're Lambda function then reads this information from the request body like any other field.

Documentation on this can be found here. Scroll down to the section titled "To enable a user pool authorizer on methods" and see step 7: "If needed, choose Integration Request to add $context.authorizer.claims ..."

0
votes

When you created the Cognito User Pool you would have created two IAM Roles. You can now setup API Gateway to pass the Identity information by

  1. Authorization set to AWS_IAM
  2. Turn on Invoke with caller credential

In Lambda you should be able to get the information in context.

Note: In the Cognito IAM Roles you need allow invoke permission for API Gateway.