Oauth error the access token is invalid

Steps to Reproduce Initialize unsplash object. Call public method Observed Behaviour Server response with 401: "OAuth error: The access token is invalid": Technical Notes As I read in uns...

@vasconita

Steps to Reproduce

  1. Initialize unsplash object.
  2. Call public method

Observed Behaviour

Server response with 401: «OAuth error: The access token is invalid»:

image

image

Technical Notes

As I read in unslplash docs, if you want to access only to public methods, you don’t need to use oauth. Instead, you have to use special headers providing your access key.

Authorization: Client-ID YOUR_ACCESS_KEY

But here we are using APPLICATION_ID instead ACCESS_KEY in the header: https://github.com/unsplash/unsplash-js/blob/master/src/utils/index.js#L32

I’m going to prepare a PR in order to fix this.

jakedex, betancourtl, Ding-Fan, grydstedt, strickland84, Prinzhorn, waldothedeveloper, branquito, francisrod01, regrettablemouse136, and 3 more reacted with thumbs up emoji

@betancourtl

Yeah I was looking at that too.

@grydstedt

Is there a workaround for this before PR is merged?

@yusufsiregar44

@mubaris1

is this fixed?? I’m getting this error too.

@ldco2016

I don’t seem to be getting anything at all. Is this fixed yet?

@mubaris1

I was using a third party node-module (universal-config, as it is used in the official example of unsplash) for storing my application id, and secret key and was getting this error because the universal-config package was wrongly loading the values.

I just did away with the universal-config, and loaded the application id and secret key to get it working.

If you’re getting this error, it’s most likely because the keys are not loading correctly. Check that.

@NightHawk451

@samira469

Still getting this error! I guess there wasn’t any fix for that yet

@Mr-Malomz

@davidreoch

@mattsrobot

having similar issue today, am I alone?

@Balasnest

Facing exact issues. Any updates?

@TromeshChalodiya

This error also occurred due to the typo of the header instead headers.
Make sure You define headers

@Tahfimul

@lukechesser

if someone can share a reproduction of the code, I’m happy to clear it up — something must not be getting configured correctly in the auth.

@marine1988

Im facing same problem here

@turalalakbarli

i passed my acces key value using a client_id query parameter in my code and it fixed

@ronakjethwa

@lukechesser

@lukechesser

@adamclark64 you’re missing the Client-ID in Authorization: Client-ID YOUR_ACCESS_KEY. You can also check by moving the auth to the client_id query param: https://api.unsplash.com/search/photos?query=dog&client_id=YOUR_ACCESS_KEY

@riyazatdurrani

This error also occurred due to the typo of the header instead headers.
Make sure You define headers

@clickwithclark

ABSOLUTELY NOT FIXED

Fixed! said by Mr-Malomz

Absolutely NOT fixed. The Authentication header is still not fixed 16-OCT-2020. I have no idea why the documentation continues to be misleading after all this time.

@lukechesser

@clickwithclark if you can provide a reproducible scenario and share it here, then we can try to help

@gauravdwivedi

I am getting the same error. I have cross checked my access token and also I do not have any typo in headers.
I am learning React and redux by Stephen from udemy.

localhost/:1 Access to XMLHttpRequest at ‘http://api.unsplash.com/search/photos?query=cars’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.
xhr.js:177 GET http://api.unsplash.com/search/photos?query=cars net::ERR_FAILED
dispatchXhrRequest @ xhr.js:177
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios. @ Axios.js:76
wrap @ bind.js:9
onSearchSubmit @ App.js:9
SearchBar.onFormSubmit @ SearchBar.js:8
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4070
executeDispatch @ react-dom.development.js:8243
processDispatchQueueItemsInOrder @ react-dom.development.js:8275
processDispatchQueue @ react-dom.development.js:8288
dispatchEventsForPlugins @ react-dom.development.js:8299
(anonymous) @ react-dom.development.js:8508
batchedEventUpdates$1 @ react-dom.development.js:22396
batchedEventUpdates @ react-dom.development.js:3745
dispatchEventForPluginEventSystem @ react-dom.development.js:8507
attemptToDispatchEvent @ react-dom.development.js:6005
dispatchEvent @ react-dom.development.js:5924
unstable_runWithPriority @ scheduler.development.js:646
runWithPriority$1 @ react-dom.development.js:11276
discreteUpdates$1 @ react-dom.development.js:22413
discreteUpdates @ react-dom.development.js:3756
dispatchDiscreteEvent @ react-dom.development.js:5889
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)

@samijaber

@gauravdwivedi you are not getting the same error. Your error message is different.

What you have is a CORS policy issue, as described by the error you copy-pasted. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more information on what CORS is and how you can handle it.

For this reason, you cannot use this library in the browser without providing a proxy. Read our docs on this exact matter.

@unsplash
unsplash

locked as resolved and limited conversation to collaborators

Dec 8, 2020

 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.

Successful Response

If the request for an access token is valid, the authorization server needs to generate an access token (and optional refresh token) and return these to the client, typically along with some additional properties about the authorization.

The response with an access token should contain the following properties:

  • access_token (required) The access token string as issued by the authorization server.
  • token_type (required) The type of token this is, typically just the string “Bearer”.
  • expires_in (recommended) If the access token expires, the server should reply with the duration of time the access token is granted for.
  • refresh_token (optional) If the access token will expire, then it is useful to return a refresh token which applications can use to obtain another access token. However, tokens issued with the implicit grant cannot be issued a refresh token.
  • scope (optional) If the scope the user granted is identical to the scope the app requested, this parameter is optional. If the granted scope is different from the requested scope, such as if the user modified the scope, then this parameter is required.

When responding with an access token, the server must also include the additional Cache-Control: no-store HTTP header to ensure clients do not cache this request.

For example, a successful token response may look like the following:

   HTTP/1.1 200 OK
   Content-Type: application/json
   Cache-Control: no-store

   {
     "access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
     "token_type":"Bearer",
     "expires_in":3600,
     "refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
     "scope":"create"
   }

Access Tokens

The format for OAuth 2.0 Bearer tokens is actually described in a separate spec, RFC 6750. There is no defined structure for the token required by the spec, so you can generate a string and implement tokens however you want. The valid characters in a bearer token are alphanumeric, and the following punctuation characters:

-._~+/

A simple implementation of Bearer Tokens is to generate a random string and store it in a database along with the associated user and scope information, or more advanced systems may use self-encoded tokens where the token string itself contains all the necessary info.

Unsuccessful Response

If the access token request is invalid, such as the redirect URL didn’t match the one used during authorization, then the server needs to return an error response.

Error responses are returned with an HTTP 400 status code (unless specified otherwise), with error and error_description parameters. The error parameter will always be one of the values listed below.

  • invalid_request – The request is missing a parameter so the server can’t proceed with the request. This may also be returned if the request includes an unsupported parameter or repeats a parameter.
  • invalid_client – Client authentication failed, such as if the request contains an invalid client ID or secret. Send an HTTP 401 response in this case.
  • invalid_grant – The authorization code (or user’s password for the password grant type) is invalid or expired. This is also the error you would return if the redirect URL given in the authorization grant does not match the URL provided in this access token request.
  • invalid_scope – For access token requests that include a scope (password or client_credentials grants), this error indicates an invalid scope value in the request.
  • unauthorized_client – This client is not authorized to use the requested grant type. For example, if you restrict which applications can use the Implicit grant, you would return this error for the other apps.
  • unsupported_grant_type – If a grant type is requested that the authorization server doesn’t recognize, use this code. Note that unknown grant types also use this specific error code rather than using the invalid_request above.

There are two optional parameters when returning an error response, error_description and error_uri. These are meant to give developers more information about the error, not intended to be shown to end users. However, keep in mind that many developers will pass this error text straight on to end users no matter how much you warn them, so it is a good idea to make sure it is at least somewhat helpful to end users as well.

The error_description parameter can only include ASCII characters, and should be a sentence or two at most describing the circumstance of the error. The error_uri is a great place to link to your API documentation for information about how to correct the specific error that was encountered.

The entire error response is returned as a JSON string, similar to the successful response. Below is an example of an error response.

HTTP/1.1 400 Bad Request
Content-Type: application/json
Cache-Control: no-store

{
  "error": "invalid_request",
  "error_description": "Request was missing the 'redirect_uri' parameter.",
  "error_uri": "See the full API docs at https://authorization-server.com/docs/access_token"
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Oauth error code is invalid or expired перевод
  • Oasis zrt 20 ошибка e1
  • Oart dll ошибка при запуске word
  • Oart dll ошибка при запуске excel
  • O h engine jdbc spi sqlexceptionhelper error relation does not exist

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

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