Search code examples
amazon-web-servicesaws-lambdaaws-api-gatewayamazon-cognitoamazon-iam

Acessing user identity in AWS Lambda


I want to use a lambda function that is only available to members of a Cognito user group. Within that function I want access the identity of the specific user that just called the function. So far, I did not get this to work.

I have created a Cognito group and have prepared an HTML-page with JS that can register, confirm and login users. Among other things, I can extract the identity token.

I also created an API in the API Gateway that is connected to a Lambda function. Setting the Authorization to the Cognito group works great and the function can only be called with a valid identity token.

However, I don't know how and if I can access the identity in the Lambda function this way. The flag "Invoke with caller credentials" can only be set with the Authorization AWS_IAM. This, in turn, requires a different Authorization in the HTTP request, but I don't know what I need to do there. Or am I moving into a completely wrong direction?

In other threads, e.g., https://forums.aws.amazon.com/thread.jspa?threadID=231032, and the documentation I found remarks about setting up a request mapping template, but I found no location in the GUI where I could do anything like that.

I'd appreciate any help on this! If any more information can help, just ask for it and I will provide as much as I can.


Solution

  • I finally got the identity of the caller via Mapping Templates.

    To use Mapping Templates via JSON format, you need to add a template "application/json". You can then click on the new entry and provide a specific template. In my case, I used

    {
        "name": "$context.authorizer.claims.name",
        "username": "$context.authorizer.claims['cognito:username']"
    }
    

    This adds the attributes name and username to the event object in the lambda call, which contain the content of the attribute name and the cognito username respectively.