如何获取Google Vertex AI服务的长期授权令牌?
解决Google Vertex AI API调用的长期令牌及401问题
核心问题梳理
- gcloud生成的OAuth令牌默认仅30分钟有效期,无法满足长期测试需求
- Vertex AI的REST API不支持API Key验证,所以用API Key会直接返回401
- Service Account返回401通常是权限配置或使用方式错误,而非方法不可行
测试场景的简便解决方案
方案1:生成最长12小时有效期的Service Account令牌
这是测试场景下最直接的方式,步骤如下:
- 准备好Service Account的JSON密钥文件(比如命名为
sa-key.json) - 用gcloud命令生成指定有效期的令牌(Google允许的最长有效期为12小时):
gcloud auth activate-service-account --key-file=sa-key.json gcloud auth print-access-token --expires-in=43200 # 43200秒=12小时
- 将生成的令牌替换到请求头中:
-X POST \ -H "Authorization: Bearer 生成的长有效期令牌" \ -H "Content-Type: application/json" \
方案2:自动刷新令牌的脚本(适合持续测试)
如果需要更长时间的持续测试,可以写简单脚本自动获取并刷新令牌,示例Python脚本(依赖google-auth库):
from google.oauth2 import service_account import requests # 配置参数 SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] SA_KEY_PATH = 'sa-key.json' VERTEX_API_URL = 'https://us-central1-aiplatform.googleapis.com/v1/projects/...' def get_valid_token(): credentials = service_account.Credentials.from_service_account_file( SA_KEY_PATH, scopes=SCOPES) credentials.refresh(requests.Request()) return credentials.token # 调用API流程 token = get_valid_token() headers = { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' } response = requests.post(VERTEX_API_URL, headers=headers, json={"你的请求体内容"}) print(response.json())
该脚本每次调用前会自动获取有效令牌,无需手动更新。
Service Account 401错误排查
如果之前用ServiceAccount返回401,优先检查以下几点:
- Service Account是否被授予
Vertex AI User或AI Platform Admin等相关权限 - 密钥文件路径是否正确、文件内容是否损坏
- 请求的API端点区域与ServiceAccount关联的资源区域是否匹配
关于API Key不可用的说明
Vertex AI属于Google Cloud私有服务,仅支持OAuth 2.0身份验证,不支持API Key,所以用API Key调用必然返回401,这是正常限制。
内容的提问来源于stack exchange,提问作者SandraIsCool
相关产品推荐
相关产品推荐

