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

GCP API Gateway JWT认证问题:无法复用Cloud Functions的Bearer令牌

解决API Gateway复用gcloud身份令牌访问Cloud Functions的问题

问题根源分析

你遇到的两个错误本质都是JWT令牌的**发行者(iss)或受众(aud)**与API Gateway的认证配置不匹配:

  • 第一个错误Audiences in Jwt are not allowed:gcloud auth print-identity-token默认生成的令牌受众是Cloud Functions的URL,但API Gateway要求令牌的受众必须包含配置中指定的允许值。
  • 第二个错误Jwt issuer is not configured:你用服务账号邮箱作为发行者,但gcloud auth print-identity-token生成的是用户身份令牌,其发行者是https://accounts.google.com,而非服务账号邮箱。

正确配置方案

1. 修正Swagger认证配置

在securityDefinitions的jwt部分添加x-google-audiences,指定API Gateway的实际访问URL,同时保留正确的发行者和JWKS地址(注意修正version字段为小写,符合Swagger 2.0规范):

swagger: "2.0"
info:
  title: ${google_api_gateway_api.api.api_id}
  description: xxxxxxxxxxxxx
  version: 0.0.1
securityDefinitions:
  jwt:
    type: "oauth2"
    authorizationUrl: ""
    flow: "implicit"
    x-google-issuer: "https://accounts.google.com"
    x-google-jwks_uri: "https://www.googleapis.com/oauth2/v3/certs"
    x-google-audiences: "https://YOUR-API-GATEWAY-URL" # 替换为你的API Gateway访问地址
schemes:
  - https
paths:
  "/items":
    get:
      x-google-backend:
        address: https://URL-OF-FUNCTION/items
      security:
        - jwt: []
      description: xxx
      operationId: "items"
      parameters: xxx
      responses: xxx

2. 生成匹配受众的身份令牌

调用gcloud命令时,必须指定--audiences参数,将令牌的受众设置为API Gateway的访问URL:

curl "https://YOUR-API-GATEWAY-URL/items" -H "Authorization: Bearer $(gcloud auth print-identity-token --audiences=https://YOUR-API-GATEWAY-URL)"

3. 验证后端认证链路

确保Cloud Functions保留原有认证策略(需身份令牌访问),API Gateway会自动将验证通过的令牌重写受众为Cloud Functions的URL,无需额外配置后端认证。

失败原因复盘

  • 方案1未配置x-google-audiences:API Gateway默认只接受受众为自身服务名的令牌,你生成的令牌受众是Cloud Functions的URL,因此被拒绝。
  • 方案2错误指定发行者:gcloud auth print-identity-token生成的是用户身份令牌,发行者为Google账号服务(https://accounts.google.com),与服务账号邮箱不匹配,导致验证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:00:05