如何在 AWS Lambda 函数中获取经过 Cognito 身份验证的用户信息?

How to get a Cognito authenticated user info in a AWS Lambda function?

我正在为我的 Angular 应用开发无服务器后端。

用户使用 AWS Cognito 进行身份验证,并且可以通过 API 网关访问 AWS Lambda 函数(使用通过 API 网关控制台生成的 SDK)。

问题:如何获取有关哪个用户正在调用 Lambda 函数的信息? Lambda 函数使用 python & boto3。

用例:我需要记录用户 activity 以符合 GDPR,因此我需要知道哪个用户正在调用 Lambda 函数。

API Gateway has recently launched support for Cognito User Pool Authorizer. Once your API methods are configured with Cognito User Pool Authorizer, you can pass unexpired ID Token in the Authorization header to your API methods.

If it’s a valid ID Token for a user of your User Pool, you can then access all the claims of ID Token in your API using ‘$context.authorizer.claims’.

For example ‘$context.authorizer.claims.email’ will return user’s email address and ‘$context.authorizer.claims.sub’ will return you user’s unique identifier.

If the ID token is expired or is invalid, Cognito User Pool Authorizer will send Unauthorized (401) response to the caller.

您可以从他们的出版物中了解到,您可以从未过期的授权 ID 令牌中获取声明 header。

我正在做完全相同的事情 - 使用用户池进行身份验证,然后使用 id_token 生成联合身份,我使用它来访问 API 网关,连接到 Lambda。 lambda 的 CloudWatch 日志显示 event.requestContext.identity 中传递的详细信息。该对象具有以下 -

"identity": {
        "cognitoIdentityPoolId": xxxx,
        "accountId": xxxxx,
        "cognitoIdentityId": xxxxxx,
        "caller": "xxxxxx:CognitoIdentityCredentials",
        "sourceIp": "x.x.x.x",
        "accessKey": "xxxxx",
        "cognitoAuthenticationType": "authenticated",
        "cognitoAuthenticationProvider": "********",
        "userArn": "*********",
        "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
        "user": "xxxxxx:CognitoIdentityCredentials"
    }

虽然我还没有弄清楚如何使用上述信息来获取实际登录的用户,但这是一个部分答案。

如果你已经解决了,请分享答案。

PS:这是一个 nodejs lambda