Benck
Benck

Reputation: 545

Get Cognito user attributes in Lambda function

I'm using AWS Amplify to create a Lambda function, REST API, and Cognito user pool. I want to retrieve the Cognito user who made the request to the endpoint so I can access their user attributes.

I selected the serverless Express template for the function:

app.js

app.post('/do-something', async (req, res) => {
  // The user pool ID is available as an environment variable.
  // I want to get the user and use their user attributes here.
});

And the client-side configuration sets the Authorization header based on the current user's token:

App.js

Amplify.configure({
  API: {
    endpoints: [
      {
        name: "sampleCloudApi",
        endpoint: "https://xyz.execute-api.us-east-1.amazonaws.com/Development",
        custom_header: async () => { 
          return { Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}` }
        }
      }
    ]
  }
});

Does the event (req.apiGateway.event) or context hold user information? Or can I use the Authorization header somehow?

Also, what would it look like to make the Cognito call inside the Lambda function? Will this need to use the Admin API?

Thanks!

Upvotes: 11

Views: 7092

Answers (3)

Jeff LOMBARDO
Jeff LOMBARDO

Reputation: 334

Globally there are two paths:

  1. the user claim is in the token the client or resource provider possess. The Token is a base64 encoded JSON Structure and the claim can be extracted as such
  2. The user claim is not into the token and exist only in Cognito, then if the Token is an Access Token, use the userInfo endpoint of Cognito https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo-endpoint.html

Upvotes: 0

artidataio
artidataio

Reputation: 361

Supposed that you have set up the API Gateway with Cognito authorizer, you can access the authenticated user attributes from your lambda's app.js file this way:

app.post('/do-something', async (req, res) => {
    req.apiGateway.event.requestContext.authorizer.claims['<user-attribute>']
});

Upvotes: 2

JTunis
JTunis

Reputation: 161

You can get the federated identity ID of the user through the Lambda context object using context.identity.cognitoIdentityId, but this will just be the ID associated with the user in the Cognito Identity Pool and not the Cognito User Pool.

The best way that I've seen to get User Pool attributes within Lambda is to use a custom authorizer, pass in the JWT token generated client-side by the SDK, and decode it server-side. After authorizing the user and decoding the JWT token, your Lambda will be able to access the User Pool attributes in context.authorizer.claims. Here's a post walking through the custom authorizer: https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/

Upvotes: 3

Related Questions