13

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.stack.imgur.com/2HXGP.png
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
Retdude
  • 131
  • 1
  • 1
  • 5
  • try authenticating using firefox and see if you still get the problem. i started havin gthe problem in one, but not in another browser. – tony gil Oct 19 '21 at 02:32

6 Answers6

10

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

Zach
  • 862
  • 11
  • 10
1

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.

Mohamed ElNady
  • 304
  • 1
  • 2
  • 8
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

0

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

0

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

Sehrish Waheed
  • 1,230
  • 14
  • 17
0

In my case I needed to change my redirect URI from

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

To

https://www.{{my-url}}/google/endpoint
Sam
  • 11
  • 2