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

时间:2017-09-08 23:00:34

标签: amazon-web-services aws-lambda aws-cognito

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

2 个答案:

答案 0 :(得分:1)

使用aws-api-gateway-client修改发送到Lambda函数的请求,以在请求标头中传递JWT ID Token。 您可能需要ensure your API gateway is configured to forward headers

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

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

使用ID Token进行身份验证后获得amazon-cognito-identity-js

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

Verify its signature在信任其有效载荷的内容之前。

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;

  ...
};

答案 1 :(得分:0)

您可以使用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);
   }
};