Google Sheets API连接报错:HttpError 403 认证权限范围不足
解决Google Sheets API 403 "Request had insufficient authentication scopes"错误
核心原因
这个错误本质是当前使用的授权凭证token.json包含的权限范围,和代码中声明的SCOPES不匹配,或是凭证未更新到最新权限。另外你的代码逻辑存在分支错误,可能导致凭证无法正确生成/刷新。
分步解决方案
1. 删除旧授权凭证文件
直接删除项目目录下的token.json文件——这个文件存储的是之前授权的旧权限,即便修改了代码中的SCOPES,旧凭证也不会自动更新权限范围。删除后重新运行代码,会触发新的授权流程,获取包含正确权限的新凭证。
2. 修正代码逻辑错误
你的代码中关于凭证加载和授权的分支逻辑存在错误,导致有效凭证时反而触发重新授权,无效凭证时可能无法正确启动授权流程。修正后的代码如下:
import os from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SPREADSHEET_ID = "-" # 替换为你的目标表格ID def main(): credentials = None # 读取已保存的凭证 if os.path.exists("token.json"): credentials = Credentials.from_authorized_user_file("token.json", SCOPES) # 处理凭证无效/不存在的情况 if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: # 刷新过期的凭证 credentials.refresh(Request()) else: # 启动授权流程获取新凭证 flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) credentials = flow.run_local_server(port=0) # 保存新凭证到文件 with open("token.json", "w") as token: token.write(credentials.to_json()) try: service = build('sheets', 'v4', credentials=credentials) sheets = service.spreadsheets() result = sheets.values().get(spreadsheetId=SPREADSHEET_ID, range="testlist!A1:C6").execute() values = result.get("values", []) for row in values: print(row) except HttpError as error: print(error) if __name__ == "__main__": main()
3. 验证Google Cloud项目配置
- 确认你的Google Cloud项目中已启用Google Sheets API(进入Cloud控制台 → API和服务 → 库 → 搜索Google Sheets API并启用)
- 若应用处于测试状态,需在OAuth同意屏幕中添加当前使用的Google账号为测试用户,否则会出现权限受限问题。
内容的提问来源于stack exchange,提问作者alexnikeron
相关产品推荐
相关产品推荐

