You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cognito用户池令牌访问受保护的Lambda函数?

如何用Cognito用户池令牌访问受保护的Lambda函数

场景说明

我正处于原型开发阶段,已经通过纯JavaScript实现了网站登录并获取Cognito用户池令牌的功能,现在需要用这个令牌访问通过Serverless框架配置了Cognito用户池授权的Lambda函数。

已完成的Serverless配置

我已经在Serverless.yml中为Lambda配置了Cognito用户池授权,配置代码如下:

events:
  - http:
      path: hello
      method: get
      authorizer:
        name: authorizer
        arn: arn:aws:cognito-idp:us-east-2:12345:userpool/us-east-2_UvCsU4UcR

该配置会自动创建API Gateway授权器并关联到指定的HTTP端点。

解决方案

之前访问Lambda时使用了错误的令牌,正确的操作步骤如下:

  1. 向https://<YOUR_COGNITO>.auth.us-east-2.amazoncognito.com/oauth2/token发送POST请求,从返回结果中提取id_token(注意不是access_token)
  2. 调用受保护的Lambda端点时,将id_token放入请求的Authorization头中,格式为Bearer <id_token>

curl调用示例

curl --request GET \
  --url https://<YOUR_API_GATEWAY_ID>.execute-api.us-east-2.amazonaws.com/dev/hello \
  --header 'Authorization: Bearer <你的id_token>'

纯JavaScript调用示例

const idToken = '你的id_token';
fetch('https://<YOUR_API_GATEWAY_ID>.execute-api.us-east-2.amazonaws.com/dev/hello', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${idToken}`
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('请求失败:', error));

无需额外配置,仅靠Serverless.yml中那三行授权配置即可完成权限校验。


内容的提问来源于stack exchange,提问作者lopass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:55:01