Google Calendar API Quickstart.py因redirect_uri末尾斜杠引发400错误
解决Google Calendar API OAuth重定向URI不匹配问题
问题场景
基于Google Calendar Python快速启动代码,仅修改flow.run_local_server的端口为4200,credentials.json中配置的重定向URI为http://localhost:4200,但运行时触发Error 400: redirect_uri_mismatch——实际请求的重定向URI带末尾斜杠http://localhost:4200/,与配置的URI不匹配。
可行解决方案
方案1:在Google Cloud Console添加带斜杠的重定向URI
- 进入Google Cloud Console的OAuth 2.0客户端ID配置页面
- 在「已授权的重定向URI」列表中,添加
http://localhost:4200/(保留原有不带斜杠的http://localhost:4200) - 保存配置后重新运行代码,即可兼容带/不带斜杠的请求
方案2:修改代码强制指定无斜杠的重定向URI
跳过run_local_server的默认URI生成逻辑,手动指定redirect_uri:
# 替换原有的flow初始化和run_local_server代码 flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES, redirect_uri="http://localhost:4200" ) creds = flow.run_local_server(port=4200)
或者在初始化flow后手动覆盖redirect_uri:
flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES ) flow.redirect_uri = "http://localhost:4200" creds = flow.run_local_server(port=4200)
方案3:同步credentials.json与控制台的URI配置
直接修改本地credentials.json,在redirect_uris数组中添加带斜杠的URI,确保与Cloud Console配置一致:
{"web":{"client_id":"***","project_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:4200", "http://localhost:4200/"],"javascript_origins":["http://localhost:4200"]}}
内容的提问来源于stack exchange,提问作者Saurabh
相关产品推荐
相关产品推荐

