2
votes

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!

1
This is how I get the user attributes from lambda requests: stackoverflow.com/questions/68918227/…hande gulec

1 Answers

0
votes

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/