通过Google Sheet API读取企业共享受限表格时遇授权错误求助
嘿,这个错误我之前帮同事排查过,大概率是域范围委派配置或者代码里的小疏漏导致的,咱们一步步来解决:
首先还原你的问题场景:
我尝试读取公司内共享给我的Google表格,改写脚本后运行了以下代码:
from apiclient import discovery from oauth2client.service_account import ServiceAccountCredentials import httplib2 scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] SERVICE_ACCOUNT_FILE = "gsheetread-293005-d7e75122e4c7.json" credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=scope) # Use the create_delegated() method and authorize the delegated credentials delegated_credentials = credentials.create_delegated('myemail@company.com') delegated_http = delegated_credentials.authorize(httplib2.Http()) google_sheet = discovery.build('spreadsheet_id', 'v3', http=delegated_http)运行后遇到错误:
oauth2client.client.HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
核心修复步骤
1. 确认域范围委派已正确配置
你用了create_delegated(),这说明你想通过服务账号模拟域内用户(也就是你的myemail@company.com)来访问资源,这必须要Google Workspace管理员开启域范围委派:
- 让管理员登录Google Workspace管理控制台,进入「安全」>「API控制」>「域范围委派」
- 检查你的服务账号对应的客户端ID是否在列表中,并且已经授权了你代码里的两个scope:
https://www.googleapis.com/auth/spreadsheets和https://www.googleapis.com/auth/drive - 如果没有,添加该客户端ID并勾选对应的权限范围,保存后等待10-15分钟让配置生效
2. 检查服务账号的权限和共享设置
- 登录Google Cloud控制台,找到你的服务账号,确认它被授予了合适的角色,比如「Editor」或者更细粒度的「Google Sheets API Editor」「Drive API Editor」
- 把服务账号的邮箱(格式一般是
xxx@你的项目ID.iam.gserviceaccount.com)添加到目标Google表格的共享列表中,至少给它「查看者」权限——别漏了这一步,否则即使授权正确,也拿不到表格数据
3. 修正discovery.build()的参数错误
你代码里这里明显写错了!第一个参数应该是服务名称'sheets',而不是你的spreadsheet_id。正确的写法是:
# 用v3版本的话 google_sheet = discovery.build('sheets', 'v3', http=delegated_http) # 更推荐用v4版本,功能更全 google_sheet = discovery.build('sheets', 'v4', http=delegated_http)
4. 验证scope的一致性
确保代码里的scope和管理员在域范围委派里配置的完全一致,没有拼写错误——哪怕少个斜杠或者字母错了,都会导致授权失败
内容的提问来源于stack exchange,提问作者Paul Nicoara
相关产品推荐
相关产品推荐

