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

问题描述 投票:0回答:3

我正在使用 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 吗?

谢谢!

amazon-web-services aws-lambda aws-api-gateway amazon-cognito aws-amplify
3个回答
3
投票

您可以使用

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/


2
投票

假设您已经使用 Cognito 授权者设置了 API 网关,您可以通过以下方式从 lambda 的 app.js 文件访问经过身份验证的用户属性:

app.post('/do-something', async (req, res) => {
    req.apiGateway.event.requestContext.authorizer.claims['<user-attribute>']
});

0
投票

全球有两条路径:

  1. 用户声明位于客户端或资源提供者拥有的令牌中。令牌是一个 base64 编码的 JSON 结构,并且可以这样提取声明
  2. 用户声明不包含在令牌中,仅存在于 Cognito 中,那么如果令牌是访问令牌,请使用 Cognito 的 userInfo 端点 https://docs.aws.amazon.com/cognito/latest/developerguide/userinfo -endpoint.html
© www.soinside.com 2019 - 2024. All rights reserved.