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

使用oauth2client.contrib.flask_util遇重定向URI不匹配错误的解决咨询

Fixing redirect_uri_mismatch with oauth2client.contrib.flask_util

It looks like your Flask app is auto-generating a callback URI using http://127.0.0.1:5000/oauth2callback instead of your desired HTTPS URL, which doesn't align with what you've configured in Google Cloud Console. Here are a few reliable ways to resolve this:

1. Force HTTPS for all generated URLs

Flask has a built-in config option that sets the default URL scheme for all auto-generated links. Add this line when setting up your app:

app.config['PREFERRED_URL_SCHEME'] = 'https'

This will make Flask (and the oauth2client library) use HTTPS when building the redirect URI, instead of falling back to the request's current scheme.

2. Handle reverse proxy scenarios (e.g., Nginx)

If your app runs behind a reverse proxy that handles SSL termination, Flask might not detect the HTTPS protocol correctly. You need to tell Flask to trust the X-Forwarded-Proto header sent by your proxy:

from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
# Trust the X-Forwarded-Proto header to recognize HTTPS requests
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)

# Rest of your configuration
app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'] = 'web_aplication.json'
oauth2 = UserOAuth2(app)

Don't forget to configure your reverse proxy to add the X-Forwarded-Proto: https header to all forwarded requests.

3. Manually specify the redirect URI

You can directly override the callback URI in your app's config to bypass any auto-generated value:

app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'] = 'web_aplication.json'
# Replace with your exact HTTPS callback URI
app.config['GOOGLE_OAUTH2_REDIRECT_URI'] = 'https://[your-app-url]/oauth2callback'
oauth2 = UserOAuth2(app)

This is the most explicit approach and guarantees the callback URI matches exactly what you've added in Google Cloud Console.

Final Check

Double-verify that the callback URI in Google Cloud Console is 100% identical to the one you're configuring—scheme (https), domain, path, and even trailing slashes all matter. A tiny discrepancy will still trigger the mismatch error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:42:20