如何在AWS Lambda中获取当前用户用户名?

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

我使用 AWS Lambda + Cognito(用户池 + 联合身份)+ API 网关。用户使用 amazon-cognito-identity-js 在 WEB 应用程序中进行身份验证,并使用 aws-api-gateway-client 调用 API。 API Gateway 方法具有 AWS_IAM 授权者。如何在 Lambda 函数中获取用户名(从用户池)?

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

您可以使用

event.identity.username

exports.handler = async (event, _, callback) => {
   try {
        console.log('event', event);
        console.log('event.identity.username', event.identity.username);
        const userId = event.identity.username;
        console.log('userId', userId);

        callback(null, true);
   } catch(e) {
       console.log(e);
       callback(e);
   }
};

2
投票

使用

aws-api-gateway-client
修改发送到 Lambda 函数的请求,以在请求标头中传递 JWT
ID Token
。 您可能需要 确保您的 API 网关配置为转发标头

apigClient.invokeApi(
  params,
  pathTemplate, 
  method,
  { { headers: { IDToken } } }, 
  body);

此处应使用 ID 令牌,因为其有效负载包含 cognito:username 字段

ID Token
是使用
amazon-cognito-identity-js
认证后得到的。

您可以在 lambda 处理函数中从请求标头解析此字段。

在信任其有效负载的内容之前验证其签名。

import { util } from 'aws-sdk/global'; exports.handler = function(event, context) { // Parse ID Token from request header const headers = event.headers; const idToken = headers.IDToken; ... };
    

0
投票
event.requestContext.authorizer.claims.用户名

这就是我从其他地方得到它的地方,它给出了 null

© www.soinside.com 2019 - 2024. All rights reserved.