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

使用AWS CDK v2创建HTTPUserPoolAuthorizer遇JWT授权器报错求助

解决AWS CDK v2中HTTPUserPoolAuthorizer的"Audience list must have at least 1 item"错误

问题本质

你遇到的错误源于:API Gateway V2的HTTP API用户池授权器(HttpUserPoolAuthorizer)底层是基于JWT授权器实现的,JWT授权器要求必须指定有效的受众(audience),也就是用户池客户端ID。你的代码虽然填了userPoolClients,但参数使用方式有误,导致CDK无法正确识别受众。

解决步骤

  • 正确传递用户池客户端对象,而非硬编码ID
    userPoolClients参数接受的是IUserPoolClient对象数组,不是字符串ID数组。硬编码ID会导致CDK无法关联到对应的用户池客户端,进而受众列表为空。正确做法是通过CDK创建用户池客户端,然后直接引用该对象:

    const userpoolIntegration = new HttpLambdaIntegration('Integration', privateLambda);
    const userPool = new UserPool(this, "TestUserPool");
    
    // 先创建用户池客户端
    const userPoolClient = new UserPoolClient(this, 'TestUserPoolClient', {
      userPool: userPool,
      // 可按需添加客户端配置,如generateSecret、oauth等
    });
    
    // 关联用户池客户端到授权器
    const httpUserPoolAuthorizer = new HttpUserPoolAuthorizer('UserPoolAuthorizer', userPool, {
      authorizerName: 'User-Pool-Authorizer',
      identitySource: ['method.request.header.Authorization'],
      userPoolClients: [userPoolClient], // 传递客户端对象而非字符串ID
      userPoolRegion: 'ap-south-1',
    });
    
    // 关联授权器到API路由
    api.addRoutes({
      integration: userpoolIntegration,
      path: '/user',
      methods: [apigatewayv2.HttpMethod.POST],
      authorizer: httpUserPoolAuthorizer,
    });
    
  • 确保用户池存在有效客户端
    如果你的用户池没有创建任何客户端,或者授权器引用的客户端不属于当前用户池,也会触发该错误。必须保证用户池至少有一个关联的客户端,且授权器正确引用它。

  • 验证区域配置一致性
    确认userPoolRegion与你的CDK栈区域一致,若用户池在跨区域,需确保配置的区域参数准确,避免因区域不匹配导致客户端无法被识别。

为什么会提示JWT授权器错误?

API Gateway V2的HTTP API用户池授权器本质是JWT授权器的封装,它自动使用用户池的JWKS端点和issuer信息来验证JWT令牌。因此在底层校验时,会遵循JWT授权器的规则,要求必须指定受众列表,这就是错误提示指向JWT授权器的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:23:26