Python本地凭据模拟GCP服务账户遇API禁用及端点配置疑问
解决GCP服务账户模拟时的403 API未启用问题(摆脱本地默认项目限制)
你遇到的403错误核心原因是:当使用本地默认凭据请求模拟服务账户时,GCP会默认关联gcloud设置的本地默认项目,检查该项目是否启用了IAM Service Account Credentials API。如果这个默认项目未启用该API,就会触发错误。
要让代码不受本地默认项目限制,关键是让模拟请求关联到目标服务账户所属的项目(而非本地默认项目),这时候就可以用到iam_endpoint_override参数。
关于iam_endpoint_override的具体含义
这个参数允许你覆盖默认的IAM Credentials API端点,将模拟请求直接指向目标服务账户所在项目的API实例。端点格式需要嵌入目标项目ID和目标服务账户邮箱,确保请求被路由到正确的项目进行API权限校验。
正确的端点格式:
https://iamcredentials.googleapis.com/v1/projects/{TARGET_PROJECT_ID}/serviceAccounts/{TARGET_PRINCIPAL}:generateAccessToken
其中:
{TARGET_PROJECT_ID}:目标服务账户所属的GCP项目ID(比如company-project-123){TARGET_PRINCIPAL}:你的目标服务账户完整邮箱(即代码中target_principal的值)
修改后的代码示例
from google.auth import impersonated_credentials import google.auth from google.auth.transport.requests import Request # 配置目标信息 TARGET_PROJECT_ID = "your-target-project-id" # 替换为目标服务账户所属项目ID TARGET_PRINCIPAL = "my-service-account@company.iam.gserviceaccount.com" scopes = ["https://www.googleapis.com/auth/cloud-platform"] request = Request() credentials, _ = google.auth.default(scopes=scopes) if not credentials.valid: try: credentials.refresh(request) except google.auth.exceptions.RefreshError: raise PermissionError( "GCP default credentials could not be refreshed. Verify your default configuration is correct." ) # 构造目标项目的IAM端点 iam_endpoint = f"https://iamcredentials.googleapis.com/v1/projects/{TARGET_PROJECT_ID}/serviceAccounts/{TARGET_PRINCIPAL}:generateAccessToken" # 创建模拟凭据时指定端点 target_credentials = impersonated_credentials.Credentials( source_credentials=credentials, target_principal=TARGET_PRINCIPAL, target_scopes=scopes, iam_endpoint_override=iam_endpoint )
必要前提条件
- 目标项目必须已经启用IAM Service Account Credentials API(可在GCP控制台的API库中搜索启用)
- 本地默认凭据(比如你的用户账号)需要在目标项目中被授予
Service Account Token Creator角色(或直接拥有iam.serviceAccounts.generateAccessToken权限),否则仍会触发权限错误
内容的提问来源于stack exchange,提问作者M. Garrigues
相关产品推荐
相关产品推荐

