【问题标题】:How to get the jwt payload in route authenticated by api gateway inside the function?如何在函数内部通过api网关认证的路由中获取jwt有效负载?
【发布时间】:2021-12-14 00:45:18
【问题描述】:

我为我的项目配置了一个网关,我在路由中添加了安全选项,它的工作原理:

我生成 jwt 令牌的函数:

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令牌,如果我不发送,网关返回错误,否则如果jwt有效,则调用我的函数。所以这行得通!

但我的问题是,我如何在 MyRoute 中恢复 api 网关生成的有效负载?

payload 应该可供我使用,或者我需要调用另一个 google api 来解码 req.headers.authorization 中的 jwt?

@John Hanley 所说的答案是使用标头 x-apigateway-api-userinfo:

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

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

我的数据有我被告知的有效载荷。

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions jwt google-api-gateway


    【解决方案1】:

    API Gateway 将在 HTTP 标头 X-Apigateway-Api-Userinfo 中转发 JWT。此标头是 Base64 URL 编码,并包含 JWT Payload。

    Receiving authenticated results in your API

    [编辑:我添加了@Vinicius 为回应我的回答而写的示例]

    const userInfo = req.headers['x-apigateway-api-userinfo']
    
    const data = Buffer.from(userInfo, 'base64').toString('utf-8')
    

    【讨论】:

    • 这对我有用,谢谢约翰!!
    • 不客气。我将您的示例添加到我的答案中。
    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2017-11-23
    • 2018-12-19
    • 2021-12-24
    相关资源
    最近更新 更多