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.
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"]"
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With