【问题标题】:Google Cloud Run: Calling from outside GCPGoogle Cloud Run:从 GCP 外部调用
【发布时间】:2020-05-29 19:21:19
【问题描述】:

我正在尝试访问安全的云运行服务。如果我在我的机器上尝试使用 SDK,它可以正常工作:

curl --header "Authorization: Bearer $(gcloud auth print-identity-token)"

但是,我无法使用 Python API 使用相同的服务帐户使其工作,我尝试使用 google-auth 获取访问令牌,但这给了我 401 身份验证错误。这是我用来尝试获取令牌的代码:

import google.auth
import google.auth.transport.requests

scopes = ['https://www.googleapis.com/auth/cloud-platform']

creds, projects = google.auth.default(scopes=scopes)
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)

# then using creds.token 

查看文档:https://cloud.google.com/run/docs/authenticating/service-to-service#calling_from_outside_gcp 它说要遵循此处的示例代码:https://cloud.google.com/iap/docs/authentication-howto#iap_make_request-python 我似乎无法遵循指南,因为它说启用 IAP 但似乎 IAP 仅适用于应用程序引擎而不适用云跑?

有人对这个有什么建议吗?

谢谢

【问题讨论】:

  • 我也尝试使用 AuthorizedSession 和凭据 google-auth.readthedocs.io/en/latest/… 这会产生 401 错误
  • 您的代码正在生成访问令牌。 Cloud Run 需要身份令牌。你是在运行这段代码吗?这会更改可能的答案和所需的权限。
  • 我现在看到我需要一个 ID 而不是访问令牌 - 我已经使用 IDTokenCredentials 来获得它。谢谢
  • 似乎我也无法使用映射到云运行服务的域。使用 run.app 生成的域使用映射域会产生 401 错误。
  • 您可以使用自定义域。但是,现在似乎有一个问题正在调查中。

标签: python google-cloud-platform google-authentication google-cloud-run


【解决方案1】:

如果您仍想获取您的 ID 令牌,并且不使用 Dan 的响应中的方法,则有一个更新的代码:

import requests
import google.auth    
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

service_url = 'example.com'
key_file = 'key.json'

credentials = service_account.IDTokenCredentials.from_service_account_file(
    key_file, target_audience=service_url)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
token = credentials.token
print('ID Token:', token)

【讨论】:

    【解决方案2】:

    好吧,似乎有一个 IDTokenCredentials 类适用于此,因为它使用 Open ID Connect ID 令牌而不是 OAuth 2.0 访问令牌:

    https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html

    from google.oauth2 import service_account
    from google.auth.transport.requests import AuthorizedSession
    
    service_url = 'example.com'
    key_file = 'key.json'
    
    credentials = service_account.IDTokenCredentials.from_service_account_file(
        key_file, target_audience=service_url)
    authed_session = AuthorizedSession(credentials)
    response = authed_session.get(service_url)
    

    这很令人困惑,因为我在文档中没有看到它,这让我想到了关于 IAP 的其他内容,我认为这些内容不适用于 Cloud Run。

    【讨论】:

    • 干得好,这对我帮助很大!你能接受答案吗? ;)
    猜你喜欢
    • 2020-08-19
    • 2020-07-14
    • 2021-10-21
    • 2021-08-29
    • 2023-02-14
    • 2020-12-02
    • 2021-05-31
    • 2021-12-11
    • 2020-05-28
    相关资源
    最近更新 更多