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

使用Google Python SDK调用G Suite组列表接口遇RefreshError求助

解决G Suite Admin API调用无access_token的问题

问题背景

使用Google Python SDK调用G Suite Admin Directory API列出群组时,抛出google.auth.exceptions.RefreshError,提示响应中仅存在id_token、无access_token。已添加大量相关权限范围(Scope),且确认账号具备组API访问权限,但问题仍未解决。

核心原因

服务账号无法直接访问G Suite目录数据,必须通过**域范围授权(Domain-Wide Delegation)**模拟域内拥有对应权限的用户,且代码中未指定要模拟的管理员账号,导致授权流程仅返回身份凭证而非访问令牌。

解决步骤

1. 配置域范围授权

  • 登录Google Admin控制台,进入安全 > API控制 > 域范围授权
  • 添加服务账号的客户端ID(可在Google Cloud控制台的服务账号详情页获取)
  • 仅添加必要的权限范围,避免冗余:
    https://www.googleapis.com/auth/admin.directory.group.readonly
    

2. 修改代码添加用户模拟

服务账号凭证需指定subject参数,即要模拟的域内管理员邮箱(该账号需具备群组查看权限),精简后的代码如下:

from __future__ import print_function

from googleapiclient.discovery import build
from google.oauth2 import service_account

# 仅保留必要权限范围
SCOPES = ['https://www.googleapis.com/auth/admin.directory.group.readonly']
SERVICE_ACCOUNT_FILE = 'privkey.json'
# 替换为你的域管理员邮箱
ADMIN_EMAIL = 'admin@your-domain.com'

def main():
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    # 配置用户模拟
    delegated_credentials = credentials.with_subject(ADMIN_EMAIL)
    
    service = build('admin', 'directory_v1', credentials=delegated_credentials)
    
    # 调用API并指定域名过滤
    results = service.groups().list(domain='your-domain.com').execute()
    groups = results.get('groups', [])
    
    if not groups:
        print('未找到群组。')
    else:
        print('群组列表:')
        for group in groups:
            print(f'{group["name"]} ({group["email"]})')

if __name__ == '__main__':
    main()

3. 验证依赖兼容性

当前使用的依赖版本兼容,确保已正确安装:

google-api-core==2.10.1
google-api-python-client==2.64.0
google-auth==2.12.0
google-auth-httplib2==0.1.0
google-auth-oauthlib==0.5.3
googleapis-common-protos==1.56.4

额外注意事项

  • 确保服务账号已启用,密钥文件(privkey.json)有效无损坏
  • 模拟的管理员账号需在Google Admin控制台中配置Admin Directory API群组查看权限
  • 避免添加不必要的权限范围,降低安全风险与授权冲突概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:50:45