[authentication] Google OAuth 2 authorization - Error: redirect_uri_mismatch

On the website https://code.google.com/apis/console I have registered my application, set up generated Client ID: and Client Secret to my app and tried to log in with Google. Unfortunately, I got the error message:

Error: redirect_uri_mismatch
The redirect URI in the request: http://127.0.0.1:3000/auth/google_oauth2/callback did not match a registered redirect URI

scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email
response_type=code
redirect_uri=http://127.0.0.1:3000/auth/google_oauth2/callback
access_type=offline
approval_prompt=force
client_id=generated_id

What does mean this message, and how can I fix it? I use the gem omniauth-google-oauth2.

This question is related to authentication oauth-2.0 google-signin

The answer is


Below are the reasons of Error: redirect_uri_mismatch issue occurs :

  1. Redirect URL field blank at your google project.
  2. Redirect URL does not match with your site
  3. Important! It will work only with working domain like example.com, book.com etc (Not work with local host or AWS LB URL)

Recommended to use domain URL


None of the above solutions worked for me. below did

change authorised Redirect urls to - https://localhost:44377/signin-google

Hope this helps someone.


I had two request URIs in the Console, http://xxxxx/client/api/spreadsheet/authredirect and http://localhost.

I tried all the top responses to this question and confirmed that none of them were my problem.

I removed localhost from the Console, updated my client_secret.json in my project, and the mismatch error went away.


In my case it was www and non-www URL. Actual site had www URL and the Authorized Redirect URIs in Google Developer Console had non-www URL. Hence, there was mismatch in redirect URI. I solved it by updating Authorized Redirect URIs in Google Developer Console to www URL.

Other common URI mismatch are:

  • Using http:// in Authorized Redirect URIs and https:// as actual URL, or vice-versa
  • Using trailing slash (http://example.com/) in Authorized Redirect URIs and not using trailing slash (http://example.com) as actual URL, or vice-versa

Here are the step-by-step screenshots of Google Developer Console so that it would be helpful for those who are getting it difficult to locate the developer console page to update redirect URIs.

  1. Go to https://console.developers.google.com

  2. Select your Project

Select your Project

  1. Click on the menu icon

Click on the menu icon

  1. Click on API Manager menu

Select API Manager menu

  1. Click on Credentials menu. And under OAuth 2.0 Client IDs, you will find your client name. In my case, it is Web Client 1. Click on it and a popup will appear where you can edit Authorized Javascript Origin and Authorized redirect URIs.

Select Credentials menu

Here is a Google article on creating project and client ID.


Make sure to check the protocol "http://" or "https://" as google checks protocol as well. Better to add both URL in the list.


The main reason for this issue will only come from chrome and chrome handles WWW and non www differently depending on how you entered your URL in the browsers and it searches from google and directly shows the results, so the redirection URL sent is different in a different case

enter image description here

Add all the possible combinations you can find the exact url sent from fiddler , the 400 error pop up will not give you the exact http and www infromation


Rails users (from the omniauth-google-oauth2 docs):

Fixing Protocol Mismatch for redirect_uri in Rails

Just set the full_host in OmniAuth based on the Rails.env.

# config/initializers/omniauth.rb

OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http://localhost:3000'

REMEMBER: Do not include the trailing "/"


This seems quite strange and annoying that no "one" solution is there. for me http://localhost:8000 did not worked out but http://localhost:8000/ worked out.


Anyone struggling to find where to set redirect urls in the new console: APIs & Auth -> Credentials -> OAuth 2.0 client IDs -> Click the link to find all your redirect urls


In my case I had to check the Client ID type for web applications/installed applications.

installed applications: http://localhost [Redirect URIs] In this case localhost simply works

web applications: You need valid domain name [Redirect URIs:]


When you register your app at https://code.google.com/apis/console and make a Client ID, you get a chance to specify one or more redirect URIs. The value of the redirect_uri parameter on your auth URI has to match one of them exactly.


I had this problem using Meteor and Ngrok, while trying to login with Google. I put the Ngrok URL in the Google Developer Console as redirect URLs, and went to the Ngrok URL page. The thing was that I didn't use Meteor's ROOT_URL when executing the app, so any redirect would go to localhost:3000 insted of the Ngrok URL. Just fixed it by adding the Ngrok URL as ROOT_URL on Meteor's configuration or by exporting it before executing the app on the terminal like: export ROOT_URL=https://my_ngrok_url


I needed to create a new client ID under APIs & Services -> Credentials -> Create credentials -> OAuth -> Other

Then I downloaded and used the client_secret.json with my command line program that is uploading to my youtube account. I was trying to use a Web App OAuth client ID which was giving me the redirect URI error in browser.


If you're using Google+ javascript button, then you have to use postmessage instead of the actual URI. It took me almost the whole day to figure this out since Google's docs do not clearly state it for some reason.


The trick is to input the right redirect url at the point of creating the ID. I found that updating the redirect url once the ID has been created via an 'Edit' just doesn't get the job done. What also worked for me is duplicating the entire 'vendor' folder and copying it to the same location where the 'oauth' file is (just until you successfully generate the token and then you can delete the duplicate 'vendor' folder). This is because trying to point to the vendor folder via '../vendor/autoload' didn't work for me.

So, delete your existing troublesome Client OAuth ID and try this approach, it will work.


for me it was because in the 'Authorized redirect URIs' list I've incorrectly put https://developers.google.com/oauthplayground/ instead of https://developers.google.com/oauthplayground (without / at the end).


The redirect url is case sensitive.

In my case I added both: http://localhost:5023/AuthCallback/IndexAsync http://localhost:5023/authcallback/indexasync


In my case, my credential Application type is "Other". So I can't find Authorized redirect URIs in the credentials page. It seems appears in Application type:"Web application". But you can click the Download JSON button to get the client_secret.json file. enter image description here

Open the json file, and you can find the parameter like this: "redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]. I choose to use http://localhost and it works fine for me.


In any flow where you retrieved an authorization code on the client side, such as the GoogleAuth.grantOfflineAccess() API, and now you want to pass the code to your server, redeem it, and store the access and refresh tokens, then you have to use the literal string postmessage instead of the redirect_uri.

For example, building on the snippet in the Ruby doc:

client_secrets = Google::APIClient::ClientSecrets.load('client_secrets.json')
auth_client = client_secrets.to_authorization
auth_client.update!(
  :scope => 'profile https://www.googleapis.com/auth/drive.metadata.readonly',
  :redirect_uri => 'postmessage' # <---- HERE
)

# Inject user's auth_code here:
auth_client.code = "4/lRCuOXzLMIzqrG4XU9RmWw8k1n3jvUgsI790Hk1s3FI"
tokens = auth_client.fetch_access_token!
# { "access_token"=>..., "expires_in"=>3587, "id_token"=>..., "refresh_token"=>..., "token_type"=>"Bearer"}

The only Google documentation to even mention postmessage is this old Google+ sign-in doc. Here's a screenshot and archive link since G+ is closing and this link will likely go away:

Legacy Google+ API DOC

It is absolutely unforgivable that the doc page for Offline Access doesn't mention this. #FacePalm


UPDATED --> WORKING for Android apps

Just use:

http://localhost/oauth2callback

if you handle your own logic without redirect link for web apps


To make it work on localhost and if using for web-server, do provide

Authorized JavaScript origins (Client ID for web appication)
e.g. http://localhost:4200

Just make sure that you are entering URL and not just a domain. So instead of: domain.com it should be domain.com/somePathWhereYouHadleYourRedirect


Checklist:

  • http or https?
  • & or &amp;?
  • trailing slash(/) or open ?
  • (CMD/CTRL)+F, search for the exact match in the credential page. If not found then search for the missing one.
  • Wait until google refreshes it. May happen in each half an hour if you are changing frequently or it may stay in the pool. For my case it was almost half an hour to take effect.

In my case I added

https://websitename.com/sociallogin/social/callback/?hauth.done=Google

in Authorized redirect URIs section and it worked for me


2015July15 - the signin that was working last week with this script on login

<script src="https://apis.google.com/js/platform.js" async defer></script>

stopped working and started causing Error 400 with Error: redirect_uri_mismatch

and in the DETAILS section: redirect_uri=storagerelay://...

i solved it by changing to:

<script src="https://apis.google.com/js/client:platform.js?onload=startApp"></script>

Let me complete @Bazyl's answer: in the message I received, they mentioned the URI "http://localhost:8080/" (which of course, seems an internal google configuration). I changed the authorized URI for that one, "http://localhost:8080/" , and the message didn't appear anymore... And the video got uploaded... The APIS documentation is VERY lame... Every time I have something working with google apis, I simply feel "lucky", but there's a lack of good documentation about it.... :( Yes, I got it working, but I don't yet understand neither why it failed, nor why it worked... There was only ONE place to confirm the URI in the web, and it got copied in the client_secrets.json... I don't get if there's a THIRD place where one should write the same URI... I find nor only the documentation but also the GUI design of Google's api quite lame...


Try to do these checks:

  1. Bundle ID in console and in your application. I prefer set Bundle ID of application like this "org.peredovik.${PRODUCT_NAME:rfc1034identifier}"
  2. Check if you added URL types at tab Info just type your Bundle ID in Identifier and URL Schemes, role set to Editor
  3. In console at cloud.google.com "APIs & auth" -> "Consent screen" fill form about your application. "Product name" is required field.

Enjoy :)


This answer is same as this Mike's answer, and Jeff's answer, both sets redirect_uri to postmessage on client side. I want to add more about the server side, and also the special circumstance applying to this configuration.

Tech Stack

Backend

Frontend

The "Code" Flow (Specifically for Google OAuth2)

Summary: React --> request social auth "code" --> request jwt token to acquire "login" status in terms of your own backend server/database.

  1. Frontend (React) uses a "Google sign in button" with responseType="code" to get an authorization code. (it's not token, not access token!)
    • The google sign in button is from react-google-login mentioned above.
    • Click on the button will bring up a popup window for user to select account. After user select one and the window closes, you'll get the code from the button's callback function.
  2. Frontend send this to backend server's JWT endpoint.
    • POST request, with { "provider": "google-oauth2", "code": "your retrieved code here", "redirect_uri": "postmessage" }
  3. For my Django server I use Django REST Framework JWT + Django REST Social Auth. Django receives the code from frontend, verify it with Google's service (done for you). Once verified, it'll send the JWT (the token) back to frontend. Frontend can now harvest the token and store it somewhere.
    • All of REST_SOCIAL_OAUTH_ABSOLUTE_REDIRECT_URI, REST_SOCIAL_DOMAIN_FROM_ORIGIN and REST_SOCIAL_OAUTH_REDIRECT_URI in Django's settings.py are unnecessary. (They are constants used by Django REST Social Auth) In short, you don't have to setup anything related to redirect url in Django. The "redirect_uri": "postmessage" in React frontend suffice. This makes sense because the social auth work you have to do on your side is all Ajax-style POST request in frontend, not submitting any form whatsoever, so actually no redirection occur by default. That's why the redirect url becomes useless if you're using the code + JWT flow, and the server-side redirect url setting is not taking any effect.
  4. The Django REST Social Auth handles account creation. This means it'll check the google account email/last first name, and see if it match any account in database. If not, it'll create one for you, using the exact email & first last name. But, the username will be something like youremailprefix717e248c5b924d60 if your email is [email protected]. It appends some random string to make a unique username. This is the default behavior, I believe you can customize it and feel free to dig into their documentation.
  5. The frontend stores that token and when it has to perform CRUD to the backend server, especially create/delete/update, if you attach the token in your Authorization header and send request to backend, Django backend will now recognize that as a login, i.e. authenticated user. Of course, if your token expire, you have to refresh it by making another request.

Oh my goodness, I've spent more than 6 hours and finally got this right! I believe this is the 1st time I saw this postmessage thing. Anyone working on a Django + DRF + JWT + Social Auth + React combination will definitely crash into this. I can't believe none of the article out there mentions this except answers here. But I really hope this post can save you tons of time if you're using the Django + React stack.


What you need to do is go back to your Developer Console and go to APIs & Auth > Consent Screen and fill that out. Specifically, the product name.


My two cents:
If using the Google_Client library do not forget to update the JSON file on your server after updating the redirect URI's.


I have frontend app and backend api.

From my backend server I was testing by hitting google api and was facing this error. During my whole time I was wondering of why should I need to give redirect_uri as this is just the backend, for frontend it makes sense.

What I was doing was giving different redirect_uri (though valid) from server (assuming this is just placeholder, it just has only to be registered to google) but my frontend url that created token code was different. So when I was passing this code in my server side testing(for which redirect-uri was different), I was facing this error.

So don't do this mistake. Make sure your frontend redirect_uri is same as your server's as google use it to validate the authenticity.


I had the same issue to authorize in Reactjs app on my local machine with port 3000.
I have added lvh.me in authorized domains and http://lvh.me:3000 for authorized origin and authorized redirect URL as shown in following images respectively.

Note: You can add multiple sites for verified domains. i-e for your local machine, staging or other environments

enter image description here

enter image description here


For my web application i corrected my mistake by writing

instead of : http://localhost:11472/authorize/
type :      http://localhost/authorize/

Don't forget to include the path after your domain and ip. In my case, I forgot:

/oauth2callback


My problem was that I had http://localhost:3000/ in the address bar and had http://127.0.0.1:3000/ in the console.developers.google.com

enter image description here

enter image description here


I had the same issue with google sign in.

I had correctly entered my callbacks in google Credential panel at google developer console here was my redirect urls :

https://www.example.com/signin-google

https://www.example.com/signin-google/

https://www.example.com/oauth2callback

https://www.example.com/oauth2callback/

Everything seems fine right? But it still didn't work until I added one more magical Url I added signin-google URL (which is default google callback) without www and problem solved.

Take it into account (depending on your domain) you may or may not need to add both with and without www URLs


beware of the extra / at the end of the url http://localhost:8000 is different from http://localhost:8000/


If you use this tutorial: https://developers.google.com/identity/sign-in/web/server-side-flow then you should use "postmessage".

In GO this fixed the problem:

confg = &oauth2.Config{
        RedirectURL:  "postmessage",
        ClientID:   ...,
        ClientSecret: ...,
        Scopes:      ...,
        Endpoint:     google.Endpoint,
}