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

查看:34
本文介绍了在 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 的 Integration Request 中选择了 Use Lambda Proxy Integration.如果您设置了它,那么所有令牌的声明都将在 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 代理集成,那么您需要在 lambda 的 Integration Request 中使用 Body Mapping Template.具有 application/json 内容类型的示例模板是:

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']"
}

这当然是期望在User Pool中有一个叫做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天全站免登陆