在 Lambda 函数中获取 Cognito 用户属性

Ben*_*nck 10 amazon-web-services amazon-cognito aws-lambda aws-api-gateway aws-amplify

我正在使用 AWS Amplify 创建 Lambda 函数、REST API 和 Cognito 用户池。我想检索向端点发出请求的 Cognito 用户,以便我可以访问他们的用户属性。

我为该功能选择了无服务器 Express 模板:

应用程序.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.
});
Run Code Online (Sandbox Code Playgroud)

客户端配置根据当前用户的令牌设置 Authorization 标头:

应用程序.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()}` }
        }
      }
    ]
  }
});
Run Code Online (Sandbox Code Playgroud)

事件 ( req.apiGateway.event) 或上下文是否保存用户信息?或者我可以以某种方式使用授权标头吗?

另外,在 Lambda 函数内进行 Cognito 调用会是什么样子?这需要使用 Admin API 吗?

谢谢!

JTu*_*nis 3

您可以使用 Lambda 上下文对象获取用户的联合身份 ID context.identity.cognitoIdentityId,但这只是与 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/