未配置返回401 Jwt颁发者的Cloud Endpoints

时间:2020-07-01 01:33:56

标签: python jwt google-cloud-endpoints google-cloud-run

我正在尝试将服务设置为服务认证,以便外部应用程序可以向Cloud Run应用程序(在Cloud Endpoints API网关之后)发出请求。

我已经遵循了Cloud Endpoints authentication between services文档,但是在尝试访问Cloud Run服务时,我仍然收到以下错误:

401:未配置Jwt颁发者

在openapi规范中,我设置了端点安全性和安全性定义:

/endpoint_1:
  get:
     ...
     security:
       - service_account: []

securityDefinitions:
  service_account:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "<service_account_email>"
    x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/<service_account_email>"
    x-google-audiences: "https://<cloud-run-service>-pjcfvhz2qq-uc.a.run.app"

然后按照Cloud Endpoints documentation所述使用ESPv2 Beta将其部署到Cloud Run。

部署完所有内容后,我试图从本地计算机运行以下脚本以生成签名的jwt并向Cloud Run服务发出请求:

import os
import json
import time
import requests
import google.auth.crypt
import google.auth.jwt

now = int(time.time())
expiry_length = 3600
sa_email = '<service_account_email>'

payload = {
    'iat': now,
    'exp': now + expiry_length,
    'iss': sa_email,
    'sub': sa_email,
    'email': sa_email,
    'aud': 'https://<cloud-run-service>-pjcfvhz2qq-uc.a.run.app',
}

file_path = "service-account.json"

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

headers = {
    'Authorization': 'Bearer {}'.format(signed_jwt.decode('utf-8')),
    'content-type': 'application/json',
}

url = "https://<cloud-run-service>-pjcfvhz2qq-uc.a.run.app/endpoint_1"
res = requests.get(url, headers=headers)
print(res.json())

获取请求的响应:

{'message':'未配置Jwt颁发者','code':401}

已在openapi规范中将发布者指定为与生成JWT所使用的发布者匹配的服务帐户电子邮件。

任何关于未配置 Jwt颁发者实际含义的指南都将受到赞赏。

2 个答案:

答案 0 :(得分:4)

我认为您需要一个Google签名的JWT令牌,而不是一个自签名的令牌。尝试以此更改代码的结尾(在signed_jwt = ...行之后)

    auth_url = "https://www.googleapis.com/oauth2/v4/token"

    params = {
        'assertion': signed_jwt, # You may need to decode the signed_jwt: signed_jwt.decode('utf-8')
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
    }

    r = requests.post(auth_url, data=params)

    if r.ok:
        id_token = r.json()['id_token']

        headers = {
            'Authorization': 'Bearer {}'.format(id_token),
            'content-type': 'application/json',
        }

        url = "https://<cloud-run-service>-pjcfvhz2qq-uc.a.run.app/endpoint_1"
        res = requests.get(url, headers=headers)
        print(res.json())

    # For debugging
    print(r)
    print(vars(r))

答案 1 :(得分:0)

您是否部署了带有“--allow-unauthenticated”标志的 ESPv2 Cloud-Run 服务?如果否,ESPv2 云运行服务受 IAM 服务器保护,它将验证 JWT 令牌并将新令牌传递给 ESPv2。 ESPv2 不会通过新令牌识别其发行者。

为了使 ESPv2 JWT 身份验证起作用,您必须通过在“gcloud run deploy”命令中传递标志“--allow-unauthenticated”来禁用 ESPv2 云运行的 IAM。