Google Cloud python 使用本地应用程序默认身份令牌对云运行进行身份验证请求

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

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

问题是我无法使用应用程序默认本地凭据令牌请求有效的承载来向 Google Cloud Run 发出授权请求。如果我从 CLI 生成 Bearer 令牌gcloud auth print-identity-token并在 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)

从谷歌身份验证文档中,我了解到 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)

bui 我收到以下错误


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

谢谢


翻过高山走不出你
浏览 132回答 2
2回答

慕运维8079593

您需要一个服务帐户才能使用 Google Auth 库生成有效的 JWT 令牌。所有库和所有语言都存在同样的问题。在本地环境中,如果您想在本地和云中使用相同的代码,则必须生成服务帐户密钥文件并将其与 ADC 一起使用。可悲的是,这是一个安全问题......

慕尼黑的夜晚无繁华

如果您想将curl命令转换为python请求,这是转换后的代码:导入请求headers = { '授权': '承载 $(gcloud auth print-identity-token)', }响应 = requests.get('http://SERVICE_URL', headers=headers)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python