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

Google Sheets API访问遇Redirect URI Mismatch错误,求排查

解决Google Sheets OAuth 2.0 redirect_uri_mismatch错误

你的问题出在客户端类型不匹配、代码与控制台URI配置冲突两个核心点,以下是具体修复步骤:

一、更换OAuth客户端ID类型

你当前的credentials.json是「Web应用」类型,但代码使用的是InstalledAppFlow(适用于本地/桌面应用),两者不兼容:

  1. 登录Google Cloud控制台,删除现有的「Web应用」类型OAuth客户端ID。
  2. 创建**「桌面应用」类型**的客户端ID,下载新的credentials.json替换原文件。新文件的根节点应为"installed"而非"web"。

二、统一重定向端口配置

代码中你手动设置了redirect_uri为http://127.0.0.1:8000,但调用run_local_server(port=0)会让程序随机选择端口,导致和控制台配置的URI不匹配,解决方法:

固定端口(推荐)

修改代码,指定固定端口,和控制台配置保持一致:

flow = InstalledAppFlow.from_client_secrets_file(
    'ApplicantList/credentials.json', SCOPES)
# 移除手动设置的redirect_uri,直接指定端口
creds = flow.run_local_server(port=8000)

同时在Google Cloud控制台的桌面应用客户端ID配置中,添加http://localhost:8000/和http://127.0.0.1:8000/作为重定向URI。

(可选)允许随机端口(不推荐)

若要保留随机端口,需在控制台添加所有可能的本地端口,这显然不现实,因此固定端口是更稳妥的方案。

三、清理冗余配置

  1. 删除本地的token.pickle文件,让程序重新触发授权流程,确保新的credentials生效。
  2. 若无需使用服务账号访问Sheets,删除Google Cloud控制台中的服务账号配置,避免混淆授权逻辑。

验证新credentials格式

正确的桌面应用类型credentials.json示例:

{
  "installed": {
    "client_id": "xxxx",
    "project_id": "xxxx",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxxx",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob",
      "http://localhost"
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:10:36