为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2023-07-27 10:32:46
我正在尝试将以下命令从 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, defaultfrom google.auth.transport.requests import AuthorizedSessionrequest_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谢谢
查看完整描述

2 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

您需要一个服务帐户才能使用 Google Auth 库生成有效的 JWT 令牌。所有库和所有语言都存在同样的问题。

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


查看完整回答
反对 回复 2023-07-27
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

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

导入请求

headers = { '授权': '承载 $(gcloud auth print-identity-token)', }

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


查看完整回答
反对 回复 2023-07-27
  • 2 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信