如何用Python获取当前gcloud配置的用户/服务账号ID令牌?
解决方案:本地与云函数通用的ID令牌获取方案
问题原因
你遇到的报错是因为google.oauth2.id_token.fetch_id_token()默认只会从元数据服务器(云函数环境自带)或服务账号凭据文件中获取身份信息,而本地通过gcloud configurations切换的是用户账号凭据,不在默认的凭据检索链中,因此无法自动识别。
可行的通用实现方案
以下代码可同时适配云函数环境和本地functions-framework运行场景:
import google.auth from google.auth.transport.requests import Request from google.oauth2.id_token import fetch_id_token def get_id_token(audience): try: # 云函数环境:直接通过元数据服务器获取ID令牌 auth_req = Request() return fetch_id_token(auth_req, audience) except google.auth.exceptions.DefaultCredentialsError: # 本地环境:加载gcloud当前配置的用户凭据 credentials, _ = google.auth.default(scopes=["openid", "email"]) # 刷新凭据确保有效性 if hasattr(credentials, "refresh"): credentials.refresh(Request()) # 使用用户凭据生成ID令牌 return fetch_id_token(credentials, audience)
关键说明
- 云函数环境:代码会优先尝试默认逻辑,直接调用元数据服务器生成令牌,和你之前的正常运行逻辑一致。
- 本地环境:当默认逻辑报错时,自动加载
gcloud当前激活配置的用户凭据,通过刷新确保凭据有效后,再生成ID令牌。 - 本地运行前提:确保已通过
gcloud auth login登录账号,且目标配置已通过gcloud config configurations activate <env_name>激活,google.auth.default()会自动读取当前配置的凭据信息。
验证方式
本地运行时,调用上述函数后可打印返回的ID令牌,和gcloud auth print-identity-token --audience <audience>命令的输出对比,确认一致性。
内容的提问来源于stack exchange,提问作者David Avikasis
相关产品推荐
相关产品推荐

