7
votes

I use AWS Lambda + Cognito (User Pool + Federated Identity) + API Gateway. Users authenticate in WEB application with amazon-cognito-identity-js and invokes API with aws-api-gateway-client. API Gateway methods have AWS_IAM authorizer. How to get username (from User Pool) in Lambda function?

2
How is this a different question from your previous post(s)? stackoverflow.com/questions/46120881/… stackoverflow.com/questions/46108431/… - Mark B
@MarkB I've removed that post - Ildar

2 Answers

2
votes

Modify the request sent to your Lambda function using aws-api-gateway-client to pass the JWT ID Token in the request header. You may need to ensure your API gateway is configured to forward headers.

apigClient.invokeApi(
  params,
  pathTemplate, 
  method,
  { { headers: { IDToken } } }, 
  body);

The ID Token should be used here as its payload contains cognito:username field

The ID Token is gotten after authentication using amazon-cognito-identity-js.

You can parse this field from the header of the request in your lambda handler function.

Verify its signature before trusting the contents of its payload.

import { util } from 'aws-sdk/global';

exports.handler = function(event, context) {
  // Parse ID Token from request header
  const headers = event.headers;
  const idToken = headers.IDToken;

  ...
};
1
votes

You can use event.identity.username

exports.handler = async (event, _, callback) => {
   try {
        console.log('event', event);
        console.log('event.identity.username', event.identity.username);
        const userId = event.identity.username;
        console.log('userId', userId);

        callback(null, true);
   } catch(e) {
       console.log(e);
       callback(e);
   }
};