无屏设备下Google OOB OAuth迁移至localhost报错的解决方法
解决无屏SSH设备上Google OAuth旧版oob失效的问题
针对你使用的google-api-python-client 1.6.2版本,以及无屏设备的场景,按以下步骤解决:
1. 修正Google Cloud控制台的OAuth配置
- 进入你的Google Cloud项目的「凭据」页面,找到对应的OAuth客户端ID(类型应为「桌面应用」)
- 在「已授权的重定向URI」列表中添加
http://localhost,保存配置 - 确保你的
client_secrets.json文件中,redirect_uris数组包含http://localhost(如果没有,手动添加后替换设备上的文件)
2. 修改Python脚本代码
在创建OAuth flow后,手动指定重定向URI,确保和控制台配置一致:
def get_authenticated_service(self, args): client_secrets_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), CLIENT_SECRET_FILE) flow = flow_from_clientsecrets( client_secrets_path, scope='https://www.googleapis.com/auth/photoslibrary', message='client_secrets files is missing' ) # 新增:手动设置重定向URI,与控制台配置一致 flow.redirect_uri = 'http://localhost' credentials = None token_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "token-oauth2.json") storage = Storage(token_path) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, storage, args) self.token = credentials.access_token return build('photoslibrary', 'v1', http=credentials.authorize(httplib2.Http()))
3. 执行授权流程(适配无屏设备)
当脚本提示授权链接时:
- 复制完整的授权URL到本地有浏览器的机器上打开
- 登录你的Google账号,完成授权后,浏览器会跳转到
http://localhost/?code=xxx&scope=xxx - 提取URL中的
code参数(即xxx部分) - 回到SSH终端,将提取到的授权码输入脚本的提示框中,完成认证
关键说明
redirect_uri_mismatch错误的核心原因是控制台配置、代码指定、授权请求中的重定向URI三者不统一,必须确保三者完全一致(包括协议、域名、端口,这里http://localhost没有端口,需保持统一)。
内容的提问来源于stack exchange,提问作者LA_
相关产品推荐
相关产品推荐

