15

I am trying to get my google authentication working on a Django app that is requesting Gmail and Calendar data. I have set up the oAuth API in the Google developer console and linked it with my project, and I've triple-checked that my redirect URI perfectly matches that in the code (No errors with HTTP vs. HTTPS nor any inconsistencies with the slashes). I made sure that my key, secret key, ClientID, and Client Secret are all configured and identical in my Django app's admin page. I have followed many youtube tutorials and searched other questions on stack overflow but Authentication is still not working. I am getting an Error 400: redirect_uri_mismatch. Even though I have checked many times to confirm that they are the same.

From all the tutorials, I have learned that there are two main origins for this error:

  1. Server sided (can be fixed in the cloud hosting developer console)
  2. Client sided (can be fixed by altering the code)

Both of these errors have their own individualized messages saying what type of mismatch it is.

Mine, however, says this: You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. \n\nIf you're the app developer, register the redirect URI in the Google Cloud Console.

Here is a photo of the error [![Google Authentication error message][1]][1]


from django.shortcuts import render, redirect
from django.http import HttpRequest
from google_auth_oauthlib.flow import Flow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from .models import CredentialsModel
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
import os


os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
#Scopes are what we should be allowed to access
SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']


"""
IF HAVING ISSUES WITH ANON USER:
Make sure you are on 127.0.0.1:8000, not localhost, both from the test-page and
the callback page. For some reason they are treated as different sessions and thus will have
issues maintaining a logged in user
"""

def oauth2callback(request):
    activeUser = request.user
    #URL is what we need to use for authentication
    authorization_response = request.build_absolute_uri()
    flow = Flow.from_client_secrets_file(
            settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
            scopes=SCOPES,

            #This is where we are redirected after authentication
            redirect_uri='http://127.0.0.1:8000/google/oauth2callback')
    #Now get proper token
    flow.fetch_token(authorization_response = authorization_response)
    #print(request.user)
    #Now save in our database
    #print(flow.credentials)
    try :
        my_credential = CredentialsModel.objects.get(pk = activeUser)
    except ObjectDoesNotExist:
        CredentialsModel.objects.create(id = activeUser, credential = flow.credentials)
    else:
        my_credential.credential = flow.credentials
        my_credential.save()

    return redirect(flow.redirect_uri)     #activeUser.get_absolute_url())


  [1]: https://i.sstatic.net/2HXGP.png
1
  • try authenticating using firefox and see if you still get the problem. i started havin gthe problem in one, but not in another browser. Commented Oct 19, 2021 at 2:32

8 Answers 8

11

google's documentation is not clear on this part (probably a bug on google's end too):

go to your GCP console, under OAuth consent screen, when the Publishing status is In production, we can still put http://localhost:8080/oauth-authorized/google under the Authorized redirect URIs without triggering the red error message saying Invalid Redirect. However, it doesn't work unless the app is in Testing status.

enter image description here

so in order to test your app at http://127.0.0.1:8000, you need to bring your GCP app to Testing status

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

hey i was dealing with this problem in ASP.Net MVC, i think the reason would be the same in php but anyways, Make sure to copy that url in ur below img to Authorized redirect URIs in OAuth 2.0 Client IDs in Google cloud console.

3 Comments

which url are you talking about?
this is the answer. Copy the url that comes with the error message you get and add it to the authorized uris in your google cloud console
@ninsau How do I add it in the Cloud Shell?
1

Copy the url that comes with the error message you get and add it to the authorize redirect uris in your google cloud console

Comments

0

Check if you are logged in to your google account.

I was using google chrome browser and turns out I was logged out of Gmail as the session expired and when I logged into Gmail and the issue was resolved

Comments

0

In my case, it working in development environment and not in production environment. Enabling API KEY for production resolved the issue.

Comments

0

IF HAVING ISSUES WITH ANON USER: Make sure you are on 127.0.0.1:8000, not localhost, both from the test-page and the callback page. For some reason they are treated as different sessions and thus will have issues maintaining a logged in user

3 Comments

This is for security reasons. localhost, 127.0.0.1 and ::1 are not the same thing even though it often might seem like they are. localhost is a domain name which has to be resolved before we can connect to it.
localhost is meant to point to the loopback interface IP addresses, that means it can point to both 127.0.0.1 (IPv4) and ::1 (IPv6). A service listening on 127.0.0.1 will not get any requests addressed to ::1, but a "dual stack" service listening on localhost might be able to take request from both addresses.
From the web server perspective, it is even possible to have two different websites being served on the same port: the first when you browse 127.0.0.1 and the second when you browse localhost -- granted the correct Host header is present in the request.
0

In my case, it was working in dev but not in prod.

Solution: enabling API KEY for production resolved the issue.

Go to Google Cloud Console > API Keys > Create Credentials - API Key

Comments

-1

In my case I needed to change my redirect URI from

https://{{my-url}}/google/endpoint

To

https://www.{{my-url}}/google/endpoint

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.