AWS API Gateway: How to pass IAM identity to Lambda function?

那年仲夏 提交于 2019-12-02 23:12:35

Support for accessing identity and other information from the Amazon API Gateway request context hadn't been available when you posted the question, but recently been added, see Announcement: Context Variables:

You can now access context variables from within mapping templates to retrieve contextual information about the API call. You can access data such as stage, resource path, and HTTP method, as well as information about the identity of the caller. This information can then be passed along to your backend integration using the $context variable. [emphasis mine]

The referenced documentation on Accessing the $context Variable features a $context Variable Reference and there are various $context.identity.* parameters that should address your use case.

Cognito Identity

As outlined in Soenke's answer to the OPs similar question in the Amazon API Gateway forum, there is an as of yet undocumented integration parameter that results in the Cognito identifier being included in this $context.identity.* context variables:

in order to have the Cognito (not IAM!) IdentityId and IdentityPoolId available in Lambda, you have to enable "Invoke with caller credentials" on the API Gateway "Integration Request" page of the API GW Resource. This results in a new context struct "identity" (containing "cognitoIdentityId" and "cognitoIdentityPoolId" being passed to the Lambda function).

You don't need that. Every Lambda function can have it's own IAM Role that grants it all required permissions in run time. This means you can grant your Lambda function any permissions it might need to perform it's operations. When you then use the AWS SDK it automatically retrieves these credentials.

See slide 22 of this AWS API Gateway presentation.

You can use Cognito with a "public" pool id, then attach role to the Cognito pool id, the role being accessing your Lambda, I think it is called InvokeLambdaRole or something

AWS.config.credentials = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: 'REGION:YOUR_POOL_ID',
});

Use AWS STS to get temporary credentials with limited privileges. After that you can use API Gateway with AWS_IAM authentication, then end point will invoke the Lambda methods for you. Or you can invoke lambda directly with the credentials you got, but then again you have to attache the right roles for the identity pool you created.

NB: Put strictly minimum roles on your pole, that is a publicly available id, every body can use it to get a temporary or a fixed (to track users accross devices) user_/app_ id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!