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

Python脚本无法访问Google Sheet,报RefreshError无效JWT签名

解决gspread访问Google Sheet时的"Invalid JWT Signature"错误

运行Python脚本访问Google Sheet时触发以下错误:

Exception has occurred: RefreshError
('invalid_grant: Invalid JWT Signature.', {'error': 'invalid_grant', 'error_description': 'Invalid JWT Signature.'})

已完成的前置操作:

  • 启用Drive API和Sheets API
  • 创建带编辑器角色的服务账号并生成JSON私钥(命名为client_secret.json)
  • 将目标Google Sheet共享给JSON文件中client_email对应的邮箱并赋予编辑器权限
  • 脚本代码如下:
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

sheet = client.open('Add stock').sheet1

clientlist = sheet.get_all_records()
print(clientlist)

解决步骤

1. 验证私钥文件完整性

  • 确认client_secret.json是从Google Cloud Console直接下载的,未手动修改过内容,尤其是private_key字段——该字段为长字符串,不能存在换行丢失、多余空格或格式错误。
  • 确保文件存放在脚本的当前工作目录下,或者在代码中使用绝对路径指定文件位置。

2. 更新API权限范围

旧的https://spreadsheets.google.com/feeds权限范围已不满足现代API要求,替换为完整的权限集合:

scope = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

3. 核对服务账号与共享权限

  • 回到Google Cloud Console,确认服务账号已被正确赋予Editor角色(至少包含Google Sheets Editor和Google Drive Editor权限)。
  • 检查目标Google Sheet的共享设置,确保服务账号邮箱已被添加且权限为「编辑器」,未被误设为「查看者」等受限权限。

4. 同步系统时间

JWT签名验证依赖准确时间戳,若本地系统时间与标准时间偏差超过5分钟,会导致签名失效。同步系统时间到标准时间服务器后重试。

5. 替换弃用的oauth2client库

oauth2client已被官方弃用,改用google-auth系列库可避免兼容性问题:
首先安装依赖:

pip install gspread google-auth google-auth-oauthlib google-auth-httplib2

修改后的脚本代码:

import gspread
from google.oauth2.service_account import Credentials

scope = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

creds = Credentials.from_service_account_file('client_secret.json', scopes=scope)
client = gspread.authorize(creds)

sheet = client.open('Add stock').sheet1
clientlist = sheet.get_all_records()
print(clientlist)

内容的提问来源于stack exchange,提问作者Pieter le Roux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:04:58