【问题标题】:Get Cognito user attributes in Lambda function在 Lambda 函数中获取 Cognito 用户属性
【发布时间】:2021-05-06 16:14:22
【问题描述】:

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

我为函数选择了无服务器 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.
});

并且客户端配置根据当前用户的token设置Authorization标头:

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) 或上下文是否包含用户信息?或者我可以以某种方式使用 Authorization 标头吗?

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

谢谢!

【问题讨论】:

标签: amazon-web-services aws-lambda aws-api-gateway amazon-cognito aws-amplify


【解决方案1】:

您可以使用 context.identity.cognitoIdentityId 通过 Lambda 上下文对象获取用户的联合身份 ID,但这只是与 Cognito 身份池中的用户关联的 ID,而不是 Cognito 用户池。

我见过的在 Lambda 中获取用户池属性的最佳方法是使用自定义授权方,传入 SDK 在客户端生成的 JWT 令牌,然后在服务器端对其进行解码。授权用户并解码 JWT 令牌后,您的 Lambda 将能够访问 context.authorizer.claims 中的用户池属性。这是一个通过自定义授权者的帖子:https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2021-12-10
    • 2015-11-26
    • 2019-01-01
    • 2018-07-17
    • 2023-02-13
    相关资源
    最近更新 更多