You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GCP服务账号配置全域委派后仍触发Client is unauthorized授权报错

问题描述

在Google Cloud Console中使用Python代码调用GCP服务时,遇到权限报错:

Client is unauthorized to retrieve access tokens using this method or client not authorized for any of the scopes requested.

已创建服务账号并添加至「Manage Domain-wide delegation」,且配置了对应Scopes,但错误仍未解决。相关代码如下:

from google.oauth2 import service_account
# 注意:原代码缺少该导入语句,会导致build函数无法使用
from googleapiclient.discovery import build

SCOPES = [
    "https://www.googleapis.com/auth/admin.directory.user",
    "https://www.googleapis.com/auth/admin.directory.domain.readonly",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/gmail.insert",
    "https://www.googleapis.com/auth/gmail.settings.sharing",
]

SERVICE_ACCOUNT_FILE = '/PATH/TO/FILE/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES, )
# 此处需替换为域内有权限的管理员邮箱
delegated_credentials = credentials.with_subject('email')
service = build('admin', 'directory_v1', credentials=delegated_credentials)

def main():
    print("Getting the first 10 users in the domain")
    results = (
        service.users()
        # 此处需替换为实际的Google Workspace客户ID
        .list(customer="customer_id", maxResults=10, orderBy="email")
        .execute()
    )
    users = results.get("users", [])
    print(users)

排查与解决建议

  • 确认委托账号权限:with_subject('email')中的邮箱必须是Google Workspace域内的超级管理员账号,或拥有Admin Directory User相关权限的账号,普通用户无法完成域级权限委托。
  • 核对Scopes配置一致性:
    1. 登录Google Workspace管理后台,进入「安全」>「API控制」>「域级委托」,找到对应服务账号的客户端ID。
    2. 确保后台配置的Scopes与代码中SCOPES列表完全一致,检查URL拼写、末尾斜杠等细节,避免遗漏或错误。
  • 验证服务账号密钥有效性:确认credentials.json是从GCP控制台服务账号页面下载的有效密钥,若密钥过期或被删除,重新生成并替换该文件。
  • 检查API启用状态:在GCP控制台的「API和服务」>「已启用的API和服务」中,确认Admin Directory API和Gmail API已启用,未启用则搜索对应API并启用。
  • 修正Customer ID:代码中customer="customer_id"需替换为实际的Google Workspace客户ID,可在Workspace管理后台「账户」>「账户设置」>「客户ID」中查看。
  • 等待权限生效:域级委托配置完成后,权限可能需要15-30分钟才能全局生效,若刚完成配置,等待一段时间后再测试。

内容的提问来源于stack exchange,提问作者Sins97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:22:14