如何用Python实现gcloud auth print-identity-token命令的等效功能?
用Python实现
gcloud auth print-identity-token的等效功能 用Google官方的google-auth和google-auth-impersonated-credentials库就能实现和你给出的gcloud命令相同的功能,具体步骤如下:
1. 安装依赖包
执行下面的命令安装所需的Python库:
pip install google-auth google-auth-impersonated-credentials
2. 编写Python代码
import google.auth from google.auth import impersonated_credentials # 替换成你的目标服务账号邮箱 TARGET_SERVICE_ACCOUNT = "my-sa@my-project.iam.gserviceaccount.com" # 替换成你的受众地址 AUDIENCE = "https://example.com" # 加载本地gcloud的默认凭据,和gcloud命令使用同一套身份验证逻辑 source_creds, _ = google.auth.default( scopes=["https://www.googleapis.com/auth/cloud-platform"] ) # 创建模拟目标服务账号的凭据,对应gcloud的--impersonate-service-account参数 impersonated_creds = impersonated_credentials.Credentials( source_credentials=source_creds, target_principal=TARGET_SERVICE_ACCOUNT, target_scopes=["https://www.googleapis.com/auth/cloud-platform"], delegates=[] ) # 生成身份令牌,指定受众并包含邮箱,对应--audiences和--include-email参数 id_token = impersonated_creds.id_token_jwt(audience=AUDIENCE, include_email=True) print(id_token)
代码说明
google.auth.default():自动读取本地gcloud配置的默认凭据,无需手动输入密钥,和gcloud命令的身份验证逻辑完全一致impersonated_credentials.Credentials():实现服务账号模拟,对应gcloud命令中的--impersonate-service-account参数id_token_jwt():生成符合要求的JWT格式身份令牌,audience参数对应--audiences,include_email=True对应--include-email参数
内容的提问来源于stack exchange,提问作者nipy
相关产品推荐
相关产品推荐

