【问题标题】:Google Cloud python autheticated request to cloud run using local application default identity token使用本地应用程序默认身份令牌对云运行的 Google Cloud python 身份验证请求
【发布时间】:2020-12-28 03:39:38
【问题描述】:

我正在尝试将 following 命令从 CLI(有效)转换为 python,但我遇到了一些问题。

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

问题是我无法请求具有 application default local credentials 令牌的有效承载向 Google Cloud Run 发出授权请求。如果我从 CLI gcloud auth print-identity-token 生成 Bearer 令牌并在 python 请求中使用它一切正常

request_url = 'https://<my endpoint>'
identity_token = '<>' # response of gcloud auth print-identity-token)
header= {'Authorization': f'Bearer {identity_token}'}
requests.get(url=request_url, headers=receiving_service_headers)

来自 google auth documentation 我了解到 Cloud Run 通信基于支持模拟身份验证的身份令牌,但我无法生成有效凭据。

from google.auth import impersonated_credentials, default
from google.auth.transport.requests import AuthorizedSession

request_url = 'https://<my endpoint>'
source_credentials, project = default()

creds = impersonated_credentials.IDTokenCredentials(
    source_credentials,
    target_audience=request_url)

authed_session = AuthorizedSession(creds)
resp = authed_session.get(request_url)
print(resp)

我收到以下错误

google.auth.exceptions.GoogleAuthError: Provided Credential must be impersonated_credentials

谢谢

【问题讨论】:

  • 用一个最小可重复的例子来编辑你的问题。例如,您没有展示如何创建凭据 (source_credentials)。你真的需要模仿吗?你在冒充什么?
  • 第二个sn-p代码可以用来重现错误。我使用default() 方法(在执行gcloud auth application-default 之后)获得本地应用程序默认凭据,我需要从此凭据身份令牌获取在授权的云运行端点上进行调用。我认为我不需要冒充,但我发现此解决方案可以作为使用应用程序默认凭据的解决方法,因为 source_credential.id_token 提供未经授权。如果我使用service_account.IDTokenCredentials.from_service_account_file 可以正常工作。

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


【解决方案1】:

今天这是不可能的。我在article 中谈到了它。您需要一个服务帐户才能使用 Google Auth 库生成有效的 JWT 令牌。所有库和所有语言都存在同样的问题。

上周,我推送了merge request in the Java auth library 来解决这个问题。我不知道为什么谷歌不自己实现它。

在您的本地环境中,如果您想在本地和云端使用相同的代码,您必须生成一个服务帐户密钥文件并将其与 ADC 一起使用。可悲的是,这是一个安全问题......

【讨论】:

    【解决方案2】:

    如果您想将 curl 命令转换为 python 请求,请关注enter link。这是转换后的代码:

    导入请求

    标题 = { 'Authorization': 'Bearer $(gcloud auth print-identity-token)', }

    response = requests.get('http://SERVICE_URL', headers=headers)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 2021-10-30
    • 2020-12-26
    • 2017-06-30
    • 2023-01-26
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多