通过HTTP请求获取Google Admin SDK API Token时遇认证错误
问题描述
每次用Python发送HTTP请求到Google Admin API时都会碰到401认证错误,错误信息如下:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "method": "ccc.hosted.frontend.directory.v1.DirectoryTokens.Get", "service": "admin.googleapis.com" } } ] } }
所有错误结果都包含以下提示:
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.
当前使用的代码:
import requests userKey = "(My User Key from the Google Cloud Service Account)" clientId = "(From my OAuth 2.0 Client IDs)" url = f"https://admin.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}" r = requests.get(url) print(r.text)
已经尝试过配置OAuth 2.0客户端ID的多个重定向URI,但问题依然存在,求解决思路。
解决思路
添加OAuth2认证头:你的请求未携带任何认证信息,Google API要求必须在请求头中加入
Authorization: Bearer {access_token},其中access_token需要通过合法的OAuth2流程获取,不能直接用服务账号ID和Client ID拼接URL认证。使用Google官方客户端库:手动用
requests处理认证容易出错,推荐使用google-auth和google-api-python-client库自动处理凭据管理:from google.oauth2 import service_account from googleapiclient.discovery import build # 替换为你的服务账号密钥文件路径 SERVICE_ACCOUNT_FILE = 'path/to/service-account.json' # 所需权限,需匹配Admin Directory API的tokens.readonly SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.security'] # 构建认证凭据,需指定要模拟的域管理员邮箱(Admin API要求域授权) credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) delegated_credentials = credentials.with_subject('admin@your-domain.com') # 构建API客户端并调用接口 service = build('admin', 'directory_v1', credentials=delegated_credentials) response = service.users().tokens().get(userKey='target-user@your-domain.com', clientId='your-client-id').execute() print(response)检查服务账号权限配置:
- 确保服务账号已在Google Workspace管理控制台中配置域范围委派,并启用了Admin Directory API的对应权限。
- 确认服务账号拥有访问目标用户令牌数据的权限(对应权限为
Admin Directory API > Users > Tokens > Read)。
区分Client ID与服务账号密钥:你当前使用的
userKey是服务账号ID,但无法直接用于认证,必须使用服务账号的JSON密钥文件生成有效凭据。
内容的提问来源于stack exchange,提问作者Samuel Kastning
相关产品推荐
相关产品推荐

