Python Google Auth OOB错误:无法切换至localhost重定向URI
解决Google OAuth OOB流被阻止问题
1. 校验client_secrets.json配置
确保配置文件为**桌面应用(Installed application)**类型,且redirect_uris包含http://localhost:3000,示例结构:
{ "installed": { "client_id": "你的客户端ID", "project_id": "你的项目ID", "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": "你的客户端密钥", "redirect_uris": [ "http://localhost:3000" ] } }
注意:若配置为web类型,即使添加localhost重定向,InstalledAppFlow仍会默认使用OOB流,必须确保是installed类型。
2. 替换代码中的认证方法
run_console()会强制触发OOB流,改用run_local_server()并指定对应端口:
from google_auth_oauthlib.flow import InstalledAppFlow # 替换为你需要的权限范围 SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=SCOPES ) # 启动本地服务器,匹配redirect_uris中的端口 credentials = flow.run_local_server( host='localhost', port=3000, authorization_prompt_message='请访问此URL完成授权: {url}', success_message='授权成功,可关闭此窗口', open_browser=True ) # 可选:保存凭据到本地,避免重复授权 with open('token.json', 'w') as f: f.write(credentials.to_json())
3. 验证Google Cloud Console的凭据配置
- 登录Google Cloud Console,进入目标项目
- 进入API和服务 > 凭据页面
- 找到对应的桌面应用凭据,确认已授权的重定向URI包含
http://localhost:3000,若缺失则添加并保存
4. 清理旧凭据缓存
如果之前生成过token.json等缓存文件,直接删除后重新运行脚本,避免旧配置干扰。
5. 更新依赖确保兼容性
当前依赖版本兼容,但可更新到最新稳定版消除潜在问题:
pip install --upgrade google-auth-oauthlib google-api-python-client oauthlib
内容的提问来源于stack exchange,提问作者Max Teiger
相关产品推荐
相关产品推荐

