Меню

Ошибка oauth как исправить

Примечание. В этих примерах показаны только ответы JSON.

Неверные учетные данные клиента

Если передан неверный _идентификатор или секрет клиента_, вы получите этот ответ об ошибке.

{
  "error": "incorrect_client_credentials",
  "error_description": "The client_id and/or client_secret passed are incorrect.",
  "error_uri": "/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#incorrect-client-credentials"
}

Чтобы устранить ошибку, убедитесь в наличии правильных учетных данных для OAuth App. Тщательно проверьте правильность значений client_id и client_secret и их передачи в GitHub.

Несоответствие URI перенаправления

Если вы указали redirect_uri, который не совпадает с зарегистрированным в OAuth App, вы получите следующее сообщение об ошибке:

{
  "error": "redirect_uri_mismatch",
  "error_description": "The redirect_uri MUST match the registered callback URL for this application.",
  "error_uri": "/apps/managing-oauth-apps/troubleshooting-authorization-request-errors/#redirect-uri-mismatch2"
}

Чтобы исправить эту ошибку, укажите redirect_uri, который соответствует зарегистрированному, или оставьте этот параметр пустым, чтобы использовался зарегистрированный по умолчанию с приложением.

Неверный код проверки

{
  "add_scopes": [
    "repo"
  ],
  "note": "admin script"
}

Если переданный код проверки неверен, просрочен или не соответствует тому, что вы получили в первом запросе на авторизацию, вы получите эту ошибку.

{
  "error": "bad_verification_code",
  "error_description": "The code passed is incorrect or expired.",
  "error_uri": "/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code"
}

Чтобы устранить ошибку, запустите процесс авторизации OAuth еще раз и получите новый код.

 Here we list the most common errors encountered in Rabobank OAuth 2.0 flow on the client side. These use cases list reason for errors and how to troubleshoot them.

During the Authorization call to get the consent of the user, the TPP may encounter the following:

Invalid client id supplied

You receive an HTTP response of 401 Unauthorized with the message invalid client id or secret while invoking an Authorization flow.

This could be caused by one of the following:

  1. Invalid client id is supplied in the request.
  2. Your TPP application is not subscribed to an API using OAuth 2.0.

To solve this issue, your application should be subscribed to an API using OAuth 2.0 and provide a valid client ID.

Redirect URI mismatch

When registering an application, you should provide a redirect URI on the Rabobank developer portal.

If you have more than one redirect URLs listed in the developer portal, make sure to provide one of the redirect URI (as provided during registration) in the redirect_uri query parameter during an Authorization call. If the redirect URI from your request does not match with the one registered on the Rabobank developer portal, you get the following error:

oauth

Requesting access token

To access the requested resources, you should exchange the received authorization code for an access token. During the retrieval of the access token, you may encounter the following:

Invalid authorization code (grant type code flow)

The authorization code should be sent to the token endpoint to get the access token. Sending an invalid authorization code (expired, invalid, or already used) results in the below error:

Http status: 400 (Bad request)
{"error": "invalid_grant"}

To avoid this error, you should pass the correct authorization code before it expires (expiry: 5 minutes). Make sure to not call the token endpoint multiple times using the same authorization code.

Adding a slight delay of 1000ms before calling this endpoint ensures that the authorization code is in sync across our servers.

Invalid refresh token

Sending invalid Refresh token to get access token results in the below error:

Http status: 401 (Unauthorized)
{"error": "invalid_grant"}

The Refresh token is valid for 30 days and can be only used once. To avoid this error, you should pass a valid Refresh token and not use the same token multiple times.

Invalid authorization header

While making a call to the token endpoint, an Authorization header should be provided consisting of a client id and client secret. If an invalid combination is passed, it results in the below error:

Http status: 401 (Unauthorized)
{"error": "invalid_client"}

To avoid this error, you should use the correct client id and client secret and make sure that the Authorization header is prepared as specified in the OAuth documentation.

Grant type missing

While making a call to the token endpoint, the grant_type query parameter should be provided. The value of this query parameter is based on the type of authorization you are passing to the endpoint.

For example, if you are swapping an authorization code for an access token the value of the parameter should be the authorization_code.

An example of the error message returned is as below:

Http status: 400 (Bad request)
{"error": "invalid_request"}

To avoid this error, make sure to provide all the required parameters, including grant_type.

Requesting resources with an access token

Access token invalid

The Access token issued by the authorization server is valid for 60 minutes for PSD2 and 24 hrs for Premium after receiving. Passing an expired or invalid Access token while accessing the resource results in the following error.

{
  "httpCode": "401",
  "httpMessage": "Unauthorized",
  "moreInformation": "This server could not verify that you are authorized to access the URL"
}

To avoid this error, you should always check the expiry time associated with the access token. If the token is expired, use a Refresh token to receive a new Access token.

If you are unable to get a new access token using the refresh token, it could be because the user consent is either expired or revoked. You can validate the consent using the Consent Details Service API.

If this is the case, you should renew the consent before proceeding.

How to check if the user consent is expired (or) revoked?

Using the information you received during the authorization flow, you can retrieve the consent by a specific Id as explained in the API Consent Details Service documentation.

If the consent status is one of the following, the consent is not valid and cannot be used to access the resources:

  • expired
  • revokedByPsu
  • terminatedByTpp
  • received
  • rejected

Using an invalid consent results in the following error:

{
  "httpCode": "403",
  "httpMessage": "Forbidden",
  "moreInformation": "CONSENT_INVALID"
}

To access the resource gain, you should follow the authorization flow again and ask the user permission(s) to the required resources.

Deactivated or Expired consent

The consent of the user may be expired or revoked by the user, while your access/refresh tokens are still active, this results in a 403 Forbidden CONSENT_INVALID error message.

You may also check the status of the consent by making a call to Consent Details Service API and re-initiate the consent flow if required.

Not having the required permission to access an API

{  
  "httpCode": "403",  
  "httpMessage": "Forbidden",  
  "moreInformation": "FORBIDDEN"
}

403 Forbidden FORBIDDEN error can be triggered if the Access token included in the request does not contain the correct scope for the API being used.

Example: You have an access token for the scope paymentRequest, but you are trying to access the Account information API, this API requires a different scope: ‘ais.balances.read’.

To avoid this error, follow the authorization flow with the correct scope required for your API.

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.

Jeff Ward's user avatar

Jeff Ward

15.1k5 gold badges46 silver badges56 bronze badges

asked Jul 14, 2012 at 16:08

user984621's user avatar

user984621user984621

45.3k72 gold badges221 silver badges397 bronze badges

3

The redirect URI (where the response is returned to) has to be registered in the APIs console, and the error is indicating that you haven’t done that, or haven’t done it correctly.

Go to the console for your project and look under API Access. You should see your client ID & client secret there, along with a list of redirect URIs. If the URI you want isn’t listed, click edit settings and add the URI to the list.

EDIT: (From a highly rated comment below) Note that updating the google api console and that change being present can take some time. Generally only a few minutes but sometimes it seems longer.

ShadowUC's user avatar

ShadowUC

6625 silver badges19 bronze badges

answered Jul 14, 2012 at 16:57

Steve Bazyl's user avatar

37

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

Note: The Authorized URI includes all localhost links by default, and any live version needs to include the full path, not just the domain, e.g. https://example.com/path/to/oauth/url

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

abdusco's user avatar

abdusco

8,8252 gold badges27 silver badges41 bronze badges

answered Dec 25, 2015 at 11:19

Mukesh Chapagain's user avatar

Mukesh ChapagainMukesh Chapagain

24.6k15 gold badges115 silver badges119 bronze badges

8

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.

Jason Watkins's user avatar

answered Sep 24, 2013 at 19:22

Mike Keskinov's user avatar

Mike KeskinovMike Keskinov

11.4k6 gold badges60 silver badges86 bronze badges

17

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

answered Jan 5, 2018 at 20:51

Jeff Ward's user avatar

Jeff WardJeff Ward

15.1k5 gold badges46 silver badges56 bronze badges

3

For my web application i corrected my mistake by writing

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

answered Oct 19, 2014 at 6:59

Guven Sezgin Kurt's user avatar

4

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

answered Feb 12, 2014 at 13:48

Chintan's user avatar

ChintanChintan

6046 silver badges15 bronze badges

1

1.you would see an error like this

enter image description here

2.then you should click on request details
enter image description here

after this , you have to copy that url and add this on https://console.cloud.google.com/

  1. go to https://console.cloud.google.com/

enter image description here
enter image description here

  1. click on Menu -> API & Services -> Credentials

enter image description here

  1. you would see a dashboard like this ,click on edit OAuth Client
    enter image description here

  2. now in Authorized Javascript Origins and Authorized redirect URLS
    add the url that has shown error called redirect_uri_mismatch i.e here it is
    http://algorithammer.herokuapp.com , so i have added that in both the places in
    Authorized Javascript Origins and Authorized redirect URLS

  3. click on save and wait for 5 min and then try to login again

answered Feb 4, 2022 at 6:54

Rohan Devaki's user avatar

Rohan DevakiRohan Devaki

2,6731 gold badge14 silver badges21 bronze badges

1

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

  • Python 3.6
  • Django 1.11
  • Django REST Framework 3.9: server as API, not rendering template, not doing much elsewhere.
  • Django REST Framework JWT 1.11
  • Django REST Social Auth < 2.1

Frontend

  • React: 16.8.3, create-react-app version 2.1.5
  • react-google-login: 5.0.2

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 youremailprefix@example.com. 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.

answered Mar 6, 2019 at 3:46

Shawn's user avatar

ShawnShawn

74512 silver badges15 bronze badges

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.

answered Mar 12, 2016 at 5:31

codezjx's user avatar

codezjxcodezjx

8,9125 gold badges46 silver badges57 bronze badges

0

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.

answered Aug 21, 2013 at 13:57

Kathir's user avatar

KathirKathir

1,20315 silver badges24 bronze badges

1

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.

answered Feb 16, 2016 at 9:07

itsazzad's user avatar

itsazzaditsazzad

6,6777 gold badges71 silver badges86 bronze badges

0

answered Sep 28, 2016 at 9:42

h3n's user avatar

h3nh3n

4115 silver badges2 bronze badges

2

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

answered Jul 12, 2017 at 7:22

wolfgang's user avatar

wolfgangwolfgang

7,04111 gold badges44 silver badges71 bronze badges

0

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).

answered Nov 13, 2018 at 20:29

Jacek Góraj's user avatar

Jacek GórajJacek Góraj

9051 gold badge10 silver badges16 bronze badges

1

It has been answered thoroughly but recently (like, a month ago) Google stopped accepting my URI and it would not worked. I know for a fact it did before because there is a user registered with it.

Anyways, the problem was the regular 400: redirect_uri_mismatch but the only difference was that it was changing from https:// to http://, and Google will not allow you to register http:// redirect URI as they are production publishing status (as opposed to localhost).

The problem was in my callback (I use Passport for auth) and I only did

callbackURL: "/register/google/redirect"

Read docs and they used a full URL, so I changed it to

callbackURL: "https://" + process.env.MY_URL+ "/register/google/redirect"

Added https localhost to my accepted URI so I could test locally, and it started working again.

TL;DR use the full URL so you know where you’re redirecting

answered Mar 30, 2021 at 21:59

luismzk's user avatar

luismzkluismzk

831 gold badge2 silver badges7 bronze badges

1

2015 July 15 — 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>

Andrii Abramov's user avatar

answered Jul 15, 2015 at 16:38

tony gil's user avatar

tony giltony gil

9,3676 gold badges76 silver badges98 bronze badges

2

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 «/»

answered Feb 23, 2016 at 3:48

brntsllvn's user avatar

brntsllvnbrntsllvn

92110 silver badges18 bronze badges

None of the above solutions worked for me. below did

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

Hope this helps someone.

answered Nov 4, 2016 at 14:54

Dheeraj Palagiri's user avatar

Dheeraj PalagiriDheeraj Palagiri

1,7993 gold badges21 silver badges45 bronze badges

1

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

answered Jul 17, 2020 at 16:25

Aindriú's user avatar

AindriúAindriú

3,3907 gold badges38 silver badges53 bronze badges

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

answered Oct 12, 2020 at 19:10

Code4Art's user avatar

Code4ArtCode4Art

6417 silver badges8 bronze badges

0

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

answered Oct 21, 2015 at 11:37

Steji's user avatar

StejiSteji

5611 gold badge6 silver badges16 bronze badges

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.

answered Feb 16, 2021 at 17:29

Alexandru Burca's user avatar

Alexandru BurcaAlexandru Burca

4171 gold badge4 silver badges14 bronze badges

2

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…

answered Aug 22, 2014 at 14:39

David L's user avatar

David LDavid L

1,04812 silver badges9 bronze badges

1

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.

answered Dec 29, 2017 at 0:41

James T.'s user avatar

James T.James T.

89010 silver badges24 bronze badges

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.

Blue's user avatar

Blue

22.2k7 gold badges56 silver badges89 bronze badges

answered Nov 18, 2018 at 11:57

omair azam's user avatar

omair azamomair azam

5006 silver badges14 bronze badges

1

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

answered Aug 31, 2019 at 11:06

Subrata Fouzdar's user avatar

I also get This error Error-400: redirect_uri_mismatch

This is not a server or Client side error but you have to only change by checking that you haven’t to added / (forward slash) at the end like this

redirecting URL list ❌:

https://developers.google.com/oauthplayground/

Do this only ✅:

https://developers.google.com/oauthplayground

answered Sep 29, 2022 at 6:39

The Gentelmen 24's user avatar

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 🙂

answered Jan 2, 2014 at 16:49

Vlad's user avatar

VladVlad

3,4171 gold badge30 silver badges24 bronze badges

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка ocr на частотнике
  • Ошибка ocl на частотнике шнайдер altivar 212