Refreshing an Access Token


When you initially received the access token, it may have included a refresh token as well as an expiration time like in the example below.

  "access_token": "AYjcyMzY3ZDhiNmJkNTY",
  "refresh_token": "RjY2NjM5NzA2OWJjuE7c",
  "token_type": "bearer",
  "expires": 3600

The presence of the refresh token means that the access token will expire and you’ll be able to get a new one without the user’s interaction.

The “expires” value is the number of seconds that the access token will be valid. It’s up to the service you’re using to decide how long access tokens will be valid, and may depend on the application or the organization’s own policies. You can use this to preemptively refresh your access tokens instead of waiting for a request with an expired token to fail.

If you make an API request and the token has expired already, you’ll get back a response indicating as such. You can check for this specific error message, and then refresh the token and try the request again.

If you’re using a JSON-based API, then it will likely return a JSON error response with the invalid_token error. In any case, the WWW-Authenticate header will also have the invalid_token error.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token"
  error_description="The access token expired"
Content-type: application/json

  "error": "invalid_token",
  "error_description": "The access token expired"

When your code recognizes this specific error, it can then make a request to the token endpoint using the refresh token it previously received, and will get back a new access token it can use to retry the original request.

To use the refresh token, make a POST request to the service’s token endpoint with grant_type=refresh_token, and include the refresh token as well as the client credentials.

POST /oauth/token HTTP/1.1


The response will be a new access token, and optionally a new refresh token, just like you received when exchanging the authorization code for an access token.

  "access_token": "BWjcyMzY3ZDhiNmJkNTY",
  "refresh_token": "Srq2NjM5NzA2OWJjuE7c",
  "token_type": "bearer",
  "expires": 3600

If you do not get back a new refresh token, then it means your existing refresh token will continue to work when the new access token expires.

Keep in mind that at any point the user can revoke an application , so your application needs to be able to handle the case when refreshing the access token also fails. At that point, you will need to prompt the user for authorization again.