如何使用 python 以编程方式获取 GCP identity-token
How to get a GCP identity-token programmatically with python
gcloud 命令行 gcloud auth print-identity-token
的 python 编程替代方案是什么?
我正在尝试通过 http 触发器调用 Google 云函数(仅适用于 auth 用户),我需要在身份验证 header 中传递身份令牌。当我 运行 GCP 应用引擎上的代码时,我的方法非常有效。但是,当我 运行 我自己机器上的程序(我可以在其中使用 gcloud 命令行 gcloud auth print-identity-token
)
创建令牌时,我很难找到一种获取此身份令牌的方法
我找到了如何根据 创建 access-token,但我没能理解如何创建 identity-token。
提前致谢!
好话题!这是一条漫长的道路,需要与 Google.
进行数月的测试和讨论
TL;DR:您无法使用您的用户凭据生成身份令牌,您需要有一个服务帐户(或模拟服务)才能生成身份令牌。
如果您有服务帐户密钥文件,我可以分享一段代码来生成身份令牌,但是生成和拥有服务帐户密钥文件在全球范围内都是一种不好的做法。
我发布了an article on this and 2 merge requests to implement an evolution in the Java Google auth library (I'm more Java developer that python developer even if I also contribute to python OSS project) here and here。 如果您想了解缺失的内容以及今天的 gcloud 命令如何工作,您可以阅读它们。
关于最新的合并请求,我了解到内部有来自 google 的东西,但到目前为止,我没有看到任何东西...
如果您有服务帐户,您可以模拟这是从 local/dev 机器获取 Python 中 ID 令牌的一种方法。
import google.auth
from google.auth.transport.requests import AuthorizedSession
def impersonated_id_token():
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
sa_to_impersonate = "<SA_NAME>@<GCP_PROJECT>.iam.gserviceaccount.com"
request_body = {"audience": "<SOME_URL>"}
response = authed_session.post( f'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{sa_to_impersonate}:generateIdToken',request_body)
return response
if __name__ == "__main__":
print(impersonated_id_token().json())
gcloud 命令行 gcloud auth print-identity-token
的 python 编程替代方案是什么?
我正在尝试通过 http 触发器调用 Google 云函数(仅适用于 auth 用户),我需要在身份验证 header 中传递身份令牌。当我 运行 GCP 应用引擎上的代码时,我的方法非常有效。但是,当我 运行 我自己机器上的程序(我可以在其中使用 gcloud 命令行 gcloud auth print-identity-token
)
我找到了如何根据
提前致谢!
好话题!这是一条漫长的道路,需要与 Google.
进行数月的测试和讨论TL;DR:您无法使用您的用户凭据生成身份令牌,您需要有一个服务帐户(或模拟服务)才能生成身份令牌。
如果您有服务帐户密钥文件,我可以分享一段代码来生成身份令牌,但是生成和拥有服务帐户密钥文件在全球范围内都是一种不好的做法。
我发布了an article on this and 2 merge requests to implement an evolution in the Java Google auth library (I'm more Java developer that python developer even if I also contribute to python OSS project) here and here。 如果您想了解缺失的内容以及今天的 gcloud 命令如何工作,您可以阅读它们。
关于最新的合并请求,我了解到内部有来自 google 的东西,但到目前为止,我没有看到任何东西...
如果您有服务帐户,您可以模拟这是从 local/dev 机器获取 Python 中 ID 令牌的一种方法。
import google.auth
from google.auth.transport.requests import AuthorizedSession
def impersonated_id_token():
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
authed_session = AuthorizedSession(credentials)
sa_to_impersonate = "<SA_NAME>@<GCP_PROJECT>.iam.gserviceaccount.com"
request_body = {"audience": "<SOME_URL>"}
response = authed_session.post( f'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{sa_to_impersonate}:generateIdToken',request_body)
return response
if __name__ == "__main__":
print(impersonated_id_token().json())