抱歉重复问题 Python 等同于 gcloud auth print-identity-token 命令
但是我没有足够的声誉来评论答案。 所以,这段代码片段对我来说效果很好,但我有一个问题——我可以使用这个功能吗:
IDTokenCredentials(icreds, target_audience=audience,include_email=True)
没有观众?
在 CLI 中,我使用此命令成功生成了令牌:
gcloud auth print-access-token --impersonate-service-account=short-live-test@my-project-id.iam.gserviceaccount.com
但是在 python 中,如果我将 audience var 保留为空字符串,或者将其从上述函数的参数中删除 - 我会收到以下错误:
Traceback (most recent call last):
File "", line 16, in <module>
id.refresh(request)
File "/home/xanathar/.local/lib/python3.9/site-packages/google/auth/impersonated_credentials.py", line 437, in refresh
id_token = response.json()["token"]
KeyError: 'token'
答案的原始代码片段:
import google.auth.transport.requests
from google.auth.impersonated_credentials import IDTokenCredentials
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
request = google.auth.transport.requests.Request()
# this var i want to skip or remove (maybe i can leave it as '*'?)
audience = 'my_audience'
creds, _ = google.auth.default(scopes=SCOPES)
icreds = google.auth.impersonated_credentials.Credentials(
source_credentials=creds,
target_principal="SA TO IMPERSONATE",
target_scopes=SCOPES)
id = IDTokenCredentials(icreds, target_audience=audience,include_email=True)
id.refresh(request)
print(id.token)