【发布时间】: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