How to get the Cognito Identity id in AWS Lambda

2020-02-20 08:06发布

How can I get the identity id of the user (logged in by AWS Cognito) that invoked an AWS Lambda function? Do I have to use the SDK on the Lambda function to get the identity id?

7条回答
Summer. ? 凉城
2楼-- · 2020-02-20 08:51

If anyone else stumbles upon this, I think this will help you a lot.

Note this only applies if you're using the Cognito User Pool Authorizer. If you want to use AWS_IAM with Cognito Identitys check out my github example https://github.com/VictorioBerra/js-cognito-auth-example (read down to EDIT area below)

If you have "Use Lambda Proxy Integration" checked then you wont have access to Request Template Mappings. But you can get to the claims inside the token in your lambda function:

exports.handler = (event, context, callback) => {
    //create a response
    const response = {
      statusCode: 200,
      body: JSON.stringify({
          "user email": event.requestContext.authorizer.claims.email,
      }),
    };
    callback(null, response);    
};

EDIT - More information for using AWS_IAM as APIG authorizer

Basically you need to have your APIG secured with AWS_IAM AND you must auth via a Cognito Federated Identity which will return a sessionToken example using user pools. This is what makes the AWS IAM credentials temporary. Now you have everything you need to auth to your APIG.

To test this, download the desktop version of postman, toss in your API URI (grab this from the stages area) and then under Authorization fill out the 5 fields you need for Sig4 signing. You will see 'event.identity' object in your lambda function is loaded up with properties such as the user object.

If you want to use the APIG auto-generated SDK it comes built in with a factory that takes the accessKey, secret, and token and signs everything for you. Same with the aws-sdk. You can init the credentials with those three items and it will automatically sign all requests for you with those temp creds. If you want to straight up manually hit your API with window.fetch, request, curl, (insert http client here) you can calculate your own Sig4 (beware it can be a little complicated or use a modern library to do it for you.

Also for the record, while doing my research I noticed that if you want to NOT use AWS_IAM as an APIG authorizer, and you want to use "Cognito Identity Pool Authorizer" which is a fancy new option in the dropdown in APIG you can still get a ton of info on the user in the lambda event if you just pass the JWT gained from a successful Cognito popl auth to the APIG as the Authorization header. Inside that JWT is a lot of attributes which you can customize in your pool settings.

IMO professional opinion I think using the AWS_IAM temp creds authorizer is preferred. This way, you can use as many different IdPs as you want in Cognito Identities (Facebook, Twitter, pools, etc.)


查看更多
登录 后发表回答