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

如何通过Cognito用户池为Access Token添加自定义声明?

给Cognito Access Token添加自定义声明的方法
  • 使用Pre Token Generation Lambda触发器
    这是Cognito官方支持的添加自定义声明的核心方式,在令牌生成前的阶段注入自定义字段:

    1. 进入AWS控制台的Cognito用户池,打开「触发器」选项卡
    2. 为「Pre Token Generation」关联一个Lambda函数
    3. 示例Lambda代码(Python):
      def lambda_handler(event, context):
          # 从事件中获取用户属性或其他上下文数据
          user_attrs = event['request']['userAttributes']
          # 向Access Token添加自定义声明
          event['response']['claimsOverrideDetails'] = {
              'claimsToAddOrOverride': {
                  'custom:user_role': user_attrs.get('custom:user_role'),
                  'custom:team': 'backend'
              }
          }
          return event
      

    注意:自定义声明建议用custom:前缀,避免和Cognito内置声明冲突

  • 关键注意点

    • Access Token的自定义声明会明文存放在JWT的payload中,不要放入敏感数据
    • 确保Lambda函数拥有足够权限,比如需要从其他服务拉取数据时要配置对应角色
    • 测试时可以用aws cognito-idp initiate-auth命令触发认证,再用JWT解析工具查看Access Token的payload是否包含自定义声明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:25:54