我正在使用 AWS Amplify 创建 Lambda 函数、REST API 和 Cognito 用户池。我想检索向端点发出请求的 Cognito 用户,以便我可以访问他们的用户属性。
我为该功能选择了 Serverless Express 模板:
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.
});
客户端配置根据当前用户的令牌设置授权标头:
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()}` }
}
}
]
}
});
事件 (
req.apiGateway.event
) 或上下文是否保存用户信息?或者我可以以某种方式使用授权标头吗?
此外,在 Lambda 函数内进行 Cognito 调用会是什么样子?这需要使用管理 API 吗?
谢谢!
您可以使用
context.identity.cognitoIdentityId
通过 Lambda 上下文对象获取用户的联合身份 ID,但这只是与 Cognito 身份池中的用户关联的 ID,而不是与 Cognito 用户池中的用户关联的 ID。
我见过的在 Lambda 中获取用户池属性的最佳方法是使用自定义授权者,传入由 SDK 生成的客户端 JWT 令牌,然后在服务器端对其进行解码。授权用户并解码 JWT 令牌后,您的 Lambda 将能够访问
context.authorizer.claims
中的用户池属性。这是一篇介绍自定义授权者的帖子:https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/
假设您已经使用 Cognito 授权者设置了 API 网关,您可以通过以下方式从 lambda 的 app.js 文件访问经过身份验证的用户属性:
app.post('/do-something', async (req, res) => {
req.apiGateway.event.requestContext.authorizer.claims['<user-attribute>']
});
全球有两条路径: