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

如何在API网关已认证路由的处理函数中获取JWT payload

背景

我为项目配置了API网关,在路由中添加的安全配置已正常运行。

生成JWT Token的函数

def generate_jwt():
    payload = {"iat": iat, "exp": exp, "iss": iss, "aud":  aud, "sub": iss, "email": iss, "company": company}

    signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
    jwt = google.auth.jwt.encode(signer, payload)

    return jwt

yaml配置文件内容

安全配置部分

securityDefinitions:
  apikey:
    type: "apiKey"
    name: "key"
    in: "header"
  bearer:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "mygserviceaccount"
    x-google-jwks_uri: "mygserviceaccount.com"
    x-google-audiences: "aud"
    x-google-jwt-locations:
      - header: "Authorization"
        value_prefix: "Bearer "

JWT校验路由配置

/MyRoute:
    post:
      description: "Route"
      operationId: "Route"
      x-google-backend:
        address: routeadress
        deadline: 360
      security:
      - bearer: []
      responses:
        200:
          description: "Success."
        400:
          description: "Bad Request."
        401:
          description: "Unauthorized."

按照上述配置,请求需要在Header中携带JWT Token,未携带时网关会返回错误,仅当JWT有效时才会调用后端函数,该流程已验证通过。

问题

如何在MyRoute对应的处理函数中获取API网关解析后的JWT payload?可以直接获取该payload,还是需要调用其他谷歌API对req.headers.authorization中携带的JWT进行解码?

解决方案

该方案由@John Hanley提供:无需额外调用谷歌API解码JWT,API网关完成JWT校验后,会自动将解析后的JWT payload做Base64编码后存入请求头x-apigateway-api-userinfo,直接读取该请求头解码即可:

const userInfo = req.headers['x-apigateway-api-userinfo']

const data = Buffer.from(userInfo, 'base64').toString('utf-8')

解码后的data中就包含所需的JWT payload内容。


内容的提问来源于stack exchange,提问作者Vinicius Spada Melo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:05