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

如何为Service Account Token扩充Google Drive存储?(Workspace场景)

解决方案:无需手动刷新令牌且获取大存储的方式

一、Google Workspace域范围委托(最优方案)

这完全匹配你当前的Workspace场景,具体操作如下:

  • 配置域权限:在Google Workspace Admin控制台中,给你的服务账号开启域范围委托,并指定需要访问的API权限范围(比如Drive、Sheets、Docs的全权限或只读权限)。
  • 模拟Workspace用户身份:在Python代码中,用服务账号密钥模拟指定的Workspace用户发起请求。此时所有API操作都会使用该用户的存储配额(比如Workspace商业版用户通常有2TB+空间),且服务账号的令牌会自动管理,完全不用手动刷新。
  • 代码示例:
from google.oauth2 import service_account
from googleapiclient.discovery import build

# 服务账号密钥文件路径
SERVICE_ACCOUNT_KEY = 'your-service-account-key.json'
# 要模拟的Workspace用户邮箱
TARGET_USER = 'user@your-workspace-domain.com'
# 需要的API权限范围
API_SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/spreadsheets']

# 加载服务账号凭据
base_credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_KEY, scopes=API_SCOPES)
# 委托到目标用户身份
delegated_creds = base_credentials.with_subject(TARGET_USER)

# 构建Drive服务并验证存储配额
drive_service = build('drive', 'v3', credentials=delegated_creds)
storage_info = drive_service.about().get(fields='storageQuota').execute()
print(storage_info)
  • 注意:被模拟的Workspace用户需要有足够的存储配额,且Admin控制台要确认服务账号已被授权模拟该用户。

二、长期有效OAuth刷新令牌方案(非Workspace场景可用)

如果没有Workspace,也可以通过配置长期刷新令牌避免手动操作:

  • 申请离线访问权限:创建OAuth客户端ID时,选择“桌面应用”或“其他”类型,请求offline访问范围。用户授权后,你会拿到一个refresh_token,这个令牌默认长期有效(除非用户手动撤销授权或被Google吊销)。
  • 自动刷新令牌:在Python代码中,用google-auth库加载包含refresh_token的授权文件,库会自动在访问令牌过期时,用refresh_token获取新的访问令牌,全程无需手动干预。
  • 代码示例:
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

API_SCOPES = ['https://www.googleapis.com/auth/drive']
# 包含refresh_token的授权文件路径
TOKEN_FILE = 'your-token-file.json'

credentials = Credentials.from_authorized_user_file(TOKEN_FILE, API_SCOPES)
# 令牌过期时会自动刷新
drive_service = build('drive', 'v3', credentials=credentials)
  • 注意:要保管好refresh_token,避免泄露或被用户撤销授权。

三、关键说明

  • 服务账号本身的15GB存储是独立且无法扩容的,必须通过模拟用户身份或使用长期刷新令牌的方式,借用普通用户/Workspace用户的存储配额。
  • Workspace场景下,域范围委托是最稳定的方案,权限完全由管理员控制,不需要依赖用户的授权操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:20:00