Vingtoft
Vingtoft

Reputation: 14586

How to get a Cognito authenticated user info in a AWS Lambda function?

I'm developing a serverless backend for my Angular app.

Users are authenticated using AWS Cognito and can access AWS Lambda functions through API Gateway (using the SDK that is generated through the API Gateway console).

Question: How can I get information about which user are invoking a Lambda function? Lambda functions are using python & boto3.

Usecase: I need to log user activity for GDPR compliance, therefore I need to know which user is invoking a Lambda function.

Upvotes: 5

Views: 6110

Answers (2)

asr9
asr9

Reputation: 2758

I am doing the exact same thing - using user pool for authentication & then using the id_token to generate federated identity which I user to hit API gateway, connected to a Lambda. CloudWatch logs for lambda show the details being passed in event.requestContext.identity. This object has the following -

"identity": {
        "cognitoIdentityPoolId": xxxx,
        "accountId": xxxxx,
        "cognitoIdentityId": xxxxxx,
        "caller": "xxxxxx:CognitoIdentityCredentials",
        "sourceIp": "x.x.x.x",
        "accessKey": "xxxxx",
        "cognitoAuthenticationType": "authenticated",
        "cognitoAuthenticationProvider": "********",
        "userArn": "*********",
        "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
        "user": "xxxxxx:CognitoIdentityCredentials"
    }

This is a partial answer though as I am yet to figure out how to use the above info to fetch which user actually logged in.

Please do share the answer if you have it worked out.

PS: this was a nodejs lambda

Upvotes: 1

harley
harley

Reputation: 394

API Gateway has recently launched support for Cognito User Pool Authorizer. Once your API methods are configured with Cognito User Pool Authorizer, you can pass unexpired ID Token in the Authorization header to your API methods.

If it’s a valid ID Token for a user of your User Pool, you can then access all the claims of ID Token in your API using ‘$context.authorizer.claims’.

For example ‘$context.authorizer.claims.email’ will return user’s email address and ‘$context.authorizer.claims.sub’ will return you user’s unique identifier.

If the ID token is expired or is invalid, Cognito User Pool Authorizer will send Unauthorized (401) response to the caller.

As you can read from their publication, you can get the claims from unexpired ID token of the authorization header.

Upvotes: 6

Related Questions