Google授权错误400: redirect_url_mismatch问题排查求助
解决OAuth 400 redirect_url_mismatch问题
首先,我注意到你的代码里有一个极易忽略的关键错误:OAuth2WebServerFlow的重定向参数名写错了——你用的是redirect_url,但这个类的正确参数名是redirect_uri。如果参数名错误,库会直接忽略你设置的URL,转而使用默认的重定向地址(大概率就是带尾部斜杠的http://localhost:8080/),这直接导致了和GCP授权URL不匹配的问题。
第一步:修复参数名错误
先把代码里的redirect_url改成redirect_uri:
flow = OAuth2WebServerFlow( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=rscope, redirect_uri='http://localhost:8080' # 这里修正为redirect_uri )
修改后重新测试,大概率能解决重定向URL不匹配的问题。如果还是不行,那可能是oauth2client库内部对URL做了规范化处理(自动添加斜杠),这时候可以试试下面的进阶方案。
进阶方案:迁移到官方推荐的Google Auth库
oauth2client已经被Google官方弃用,不再维护,推荐使用google-auth和google-auth-oauthlib库来处理OAuth认证,这两个库配置更灵活,也能避免旧库的各种奇怪问题。
步骤1:安装新库
pip install google-auth google-auth-oauthlib google-auth-httplib2 gspread
步骤2:重写认证代码
替换原来的oauth2client相关代码,用新库实现认证:
import gspread from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os # 定义权限范围 SCOPES = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] def get_credentials(): creds = None # 存储凭证的文件,替换成你的路径 token_file = 'token.json' # 如果之前已经保存过凭证,直接加载 if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # 如果没有有效凭证,重新认证 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: # 这里需要你的客户端密钥文件(从GCP下载的json文件,不是手动填ID和Secret) flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', SCOPES, redirect_uri='http://localhost:8080' # 严格匹配GCP授权的URL ) creds = flow.run_local_server(port=8080, open_browser=True) # 保存凭证供下次使用 with open(token_file, 'w') as token: token.write(creds.to_json()) return creds # 认证并连接Google Sheets gc = gspread.authorize(get_credentials())
注意事项
- 从GCP控制台下载你的客户端密钥文件(JSON格式),命名为
client_secret.json放在脚本同目录下,不要手动填写ID和Secret,避免出错。 run_local_server方法里指定port=8080,并且redirect_uri严格设置为http://localhost:8080(无尾部斜杠),新库会严格按照你设置的URL发起请求,不会自动添加斜杠。
额外排查点
如果还是遇到问题,可以检查:
- GCP控制台里的已授权重定向URI是否确实是
http://localhost:8080(无斜杠),并且确保是在「OAuth 2.0 客户端ID」下配置的,不是JavaScript源(JavaScript源是用于前端应用的,你的脚本是后端/桌面应用,应该配置在客户端ID的重定向URI里)。 - 清除本地的旧凭证文件(
mycredentials.csv或者新的token.json),重新发起认证,避免旧的错误凭证干扰。
内容的提问来源于stack exchange,提问作者user10007958
相关产品推荐
相关产品推荐

