基于Django实现谷歌登录时出现redirect_uri_mismatch错误求助
Hey there, let's tackle that redirect_uri_mismatch error you're hitting with Google OAuth2 in your Django project. I've dealt with this exact issue multiple times, so here's a step-by-step breakdown of what to check:
1. Verify Redirect URIs in Google Cloud Console
First, head over to your project in Google Cloud Console's API & Services → Credentials section, and find the OAuth 2.0 Client ID you created for your Django app.
- Ensure the Authorized redirect URIs list includes the exact URI your app is sending to Google. For local development, this will typically be:
http://localhost:8000/complete/google-oauth2/http://127.0.0.1:8000/complete/google-oauth2/
- For production, replace
localhost:8000with your actual domain (e.g.,https://yourdomain.com/complete/google-oauth2/). - Critical note: Google enforces strict exact matching—check that HTTP/HTTPS matches, the port is correct, and even trailing slashes are included exactly as your app sends them.
2. Validate Django Social Auth Settings
Double-check your settings.py configuration for social auth:
- Confirm
SOCIAL_AUTH_GOOGLE_OAUTH2_KEYandSOCIAL_AUTH_GOOGLE_OAUTH2_SECRETmatch the Client ID and Client Secret from Google Console exactly (no extra spaces or typos!). - Set
SOCIAL_AUTH_REDIRECT_IS_HTTPSappropriately:Trueif your production site uses HTTPSFalsefor local development (this is the default, but it's worth verifying)
- Ensure your
AUTHENTICATION_BACKENDSincludessocial.backends.google.GoogleOAuth2(which you already have, great job!).
3. Clear Browser Cache & Cookies
Old cached OAuth sessions can sometimes cause unexpected mismatches. Clear your browser's cache and cookies for your local domain (or production site) then try the Google login flow again.
4. Inspect the Redirect URI in Your Request
Use your browser's developer tools (Network tab) to check the actual redirect URI being sent to Google:
- Click the Google login button in your app
- Look for the request to
accounts.google.com/o/oauth2/v2/auth - Check the
redirect_uriparameter in the request URL - Compare this URI exactly to what's listed in your Google Console—any discrepancy (even a single character) will trigger the error.
5. Confirm the Correct OAuth Client Type
When you created your Client ID in Google Console, did you select Web application as the application type? If you chose Desktop app, iOS, or another type, it won't work for a web-based Django app. If needed, delete the existing Client ID and create a new one with the correct type.
Once you've gone through these checks, restart your Django server and test the Google login flow again. This should resolve the redirect mismatch issue.
内容的提问来源于stack exchange,提问作者Chandan

