在Lambda函数中获取Cognito用户池身份 [英] Get Cognito user pool identity in Lambda function

查看:197
本文介绍了在Lambda函数中获取Cognito用户池身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Lambda函数来处理由API网关触发的POST请求。后者被设置为通过Cognito用户池授权者进行授权。授权有效-如果我传递用户的ID令牌,则请求得到处理,如果我没有得到401。

I have a Lambda function handling POST requests triggered by the API Gateway. The latter is set up to authorize via a Cognito user pool authorizer. Authorization works - if I pass a user's ID token, the request is processed, if I don't I get a 401.

但是,我无法获得授权Lambda函数中的用户身份。所有文档使我相信应该在上下文中,但事实并非如此。我也无法在其中映射。而且,似乎也没有一种方法可以查询给定ID令牌的用户的用户池。

However, I can't get the authorized user's identity in the Lambda function. All documentation makes me believe that it should be in the context, but it isn't. I can't map it in there, either. What's more, there doesn't seem to be a way to query the user pool for a user given their ID token, either.

我是否需要身份池来完成这个?如果是这样,那如何运作?为何API网关不会自动传递用户的身份?

Do I need an identity pool to accomplish this? If so, how does that work? And why wouldn't the API gateway automatically pass on the user's identity?

推荐答案

这取决于您是否拥有将在集成请求中选择的Lambda代理集成用于lambda。如果已设置,则所有令牌的声明将通过 event.requestContext.authorizer.claims 传递。

It depends on if you have Use Lambda Proxy Integration selected in the Integration Request for the lambda. If you have it set then all the token's claims will be passed through on event.requestContext.authorizer.claims.

如果您不使用Lambda代理集成,则需要在集成请求 Body映射模板中使用lambda。具有 application / json Content-Type的示例模板为:

If you are not using Lambda Proxy Integration then you need to use a Body Mapping Template in the Integration Request for the lambda. An example template with the application/json Content-Type is:

"context" : {
    "sub" : "$context.authorizer.claims.sub",
    "username" : "$context.authorizer.claims['cognito:username']",
    "email" : "$context.authorizer.claims.email",
    "userId" : "$context.authorizer.claims['custom:userId']"
}

这当然是希望在用户池中有一个名为userId的自定义属性,并且客户端可以读取它们。

This is expecting that there is a custom attribute called userId in the User Pool of course, and they are readable by the client.

您不能对aws cognito-idp API使用id令牌,需要使用访问令牌。但是,如果您的lambda已获得授权,则可以将AdminGetUser调用与用户名一起使用。

You cannot use the id token against the aws cognito-idp APIs, you need to use the access token. You can however use AdminGetUser call with the username, if your lambda is authorized.

这篇关于在Lambda函数中获取Cognito用户池身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆