Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS API Gateway + Cognito + Lambda - $context.authorizer.principalId empty

I have a typical AWS setup, using API Gateway with Cognito user pool authentication and integrated with Lambda functions.

It all works fine, but now I need to be able to get the authenticated user id inside Lambda.

I've saw lots of questions/answers about that on SO, but none which helped to get this done. The closest one is this answer which links to this documentation.

From these links above, I understand that I should access some property of "$context.authorizer.claims" on my mapping template to get user id, but I couldn't find a list of the available properties or which one should be used.

I've also tried to use "$context.authorizer.principalId" but this does only return an empty string.

I'm currently using API gateway "Method Request passthrough" mapping template, but have tried many different mapping templates so far.

What am I missing or doing wrong here?

Please let me know if any further information is required.

like image 428
GCSDC Avatar asked May 01 '19 18:05

GCSDC


2 Answers

I suggest using the Lambda Proxy Integration. In this case, the event your Lambda receives looks like this:

{
...
  "requestContext": {
      "resourceId": "...",
      "authorizer": {
          "claims": {
              "sub": "<COGNITO SUB>",
              "iss": "...",
              "cognito:username": "<COGNITO USERNAME>",
              "aud": "...",
              "token_use": "id",
              "auth_time": "...",
              "exp": "...",
              "iat": "..."
              ...
          }
      },
      ...
  }
  ...
}

The sub is located at event.requestContext.authorizer.claims.sub and the username at event.requestContext.authorizer.claims['cognito:username'].

If using a mapping template, you can do:

{
  "sub": "$context.authorizer.claims.sub",
  "username": "$context.authorizer.claims["cognito:username"]"
}
like image 127
jogold Avatar answered Nov 04 '22 18:11

jogold


For those who face this issue. "$context.authorizer.*" will always return empty until you are testing it with AWS Api Gateway / Lambda test. Just test it with external tools like Postman and it will be populated.

like image 32
Ihor Pavlyk Avatar answered Nov 04 '22 17:11

Ihor Pavlyk