Refresh Tokens - OAuth 2.0 Simplified (2024)

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_in” 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 could use this timestamp to preemptively refresh your access tokens instead of waiting for a request with an expired token to fail. Some people like to get a new access token shortly before the current one will expire in order to save an HTTP request of an API call failing. While that is a perfectly fine optimization, it doesn’t stop you from still needing to handle the case where an API call fails if an access token expires before the expected time. Access tokens can expire for many reasons, such as the user revoking an app, or if the authorization server expires all tokens when a user changes their password.

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

HTTP/1.1 401 UnauthorizedWWW-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 application 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 if required.

POST /oauth/token HTTP/1.1Host: authorization-server.comgrant_type=refresh_token&refresh_token=xxxxxxxxxxx&client_id=xxxxxxxxxx&client_secret=xxxxxxxxxx

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.

The most secure option is for the authorization server to issue a new refresh token each time one is used. This is the recommendation in the latest Security Best Current Practice which enables authorization servers to detect if a refresh token is stolen. This is especially important for clients that don’t have a client secret, since the refresh token becomes the only thing needed to get new access tokens.

When the refresh token changes after each use, if the authorization server ever detects a refresh token was used twice, it means it has likely been copied and is being used by an attacker, and the authorization server can revoke all access tokens and refresh tokens associated with it immediately.

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 using the refresh token also fails. At that point, you will need to prompt the user for authorization again, beginning a new OAuth flow from scratch.

You might notice that the “expires_in” property refers to the access token, not the refresh token. The expiration time of the refresh token is intentionally never communicated to the client. This is because the client has no actionable steps it can take even if it were able to know when the refresh token would expire. There are also many reasons refresh tokens may expire prior to any expected lifetime of them as well.

If a refresh token expires for any reason, then the only action the application can take is to ask the user to log in again, starting a new OAuth flow from scratch, which will issue a new access token and refresh token to the application. That’s the reason it doesn’t matter whether the application knows the expected lifetime of the refresh token, because regardless of the reason it expires the outcome is always the same.

Refresh Tokens - OAuth 2.0 Simplified (2024)

FAQs

What is the best practice for refresh token expiration? ›

Best practice

Set the expiration time for refresh tokens in such a way that it is valid for a little longer period than the access tokens. For example, if you set 30 minutes for access token then set (at least) 24 hours for the refresh token.

What is the difference between access tokens and refresh tokens? ›

Refresh tokens extend the lifespan of an access token. Typically, they're issued alongside access tokens, allowing additional access tokens to be granted when the live access token expires. They're usually stored securely on the authorization server itself.

How do I force refresh my access token? ›

To refresh your access token and an ID token, you send a token request with a grant_type of refresh_token . Be sure to include the openid scope when you want to refresh the ID token. If the refresh token is valid, then you get back a new access token, a new ID token, and the refresh token.

Why is refresh token more secure than access token? ›

A refresh token is only sent to an authorization server and is therefore more secure.

Is refresh token a good practice? ›

Benefits and best practices

Enhanced security: Long-lived refresh tokens reduce the risk of access token theft, as the tokens used to access resources are short-lived and expire quickly.

How long should refresh tokens last? ›

Refresh tokens have a longer lifetime than access tokens. The default lifetime for the refresh tokens is 24 hours for single page apps and 90 days for all other scenarios. Refresh tokens replace themselves with a fresh token upon every use.

How does refresh token work in OAuth2? ›

A refresh token must not allow the client to gain any access beyond the scope of the original grant. The refresh token exists to enable authorization servers to use short lifetimes for access tokens without needing to involve the user when the token expires.

What are the advantages of refresh tokens? ›

In OAuth 2.0 authorization frameworks, refresh tokens allow developers to manage users' sessions across native, web-based, and single-page apps. Additionally, they allow users to log in and stay connected without providing their passwords for long periods.

Should refresh tokens be reused? ›

The problem is that multiple loaders may try to refresh the access token at the same time. These concurrent requests may happen within a few milliseconds. However once the refresh token is used to retrieve a new access token it cannot be reused, which causes the subsequent requests with the same refresh token to fail.

Can we decode a refresh token? ›

@bsrour You don't “decode” a refresh token. Refresh tokens are just strings. You use refresh tokens to extend the lifetime of an OAuth access token. If either the access token or refresh token have expired, then the user will need to authorise your application again.

What if a refresh token is stolen? ›

If refresh tokens never expire, then a malicious actor with a stolen refresh token can easily get persistent access to the token's resources. But if refresh tokens do expire, then apps that should have persistent access to certain resources will need a way to do that. Enter: token rotation.

Where is the primary refresh token stored? ›

Primary Refresh Token (PRT) Usage

Windows: In Windows, PRT is used in Azure AD authenticated apps for SSO and is stored securely in the Credential Manager. Android Enterprise: For Android Enterprise, PRT is used in Azure AD authenticated apps for SSO and is stored securely in the Keystore System.

Can I use refresh token instead of access token? ›

The access token is used to authenticate API requests to access protected resources, while the refresh token is used to obtain new access tokens once the current ones expire.

Why separate access token and refresh token? ›

Refresh tokens are designed to be long-lived but must be revoked at need. Access tokens are designed to be short-lived, because they can't be revoked (in most cases).

Does a refresh token need to be encrypted? ›

There is no point to encrypting the refresh token in the client unless you have some way to generate a key that isn't stored by the browser.

What is refresh token expiration policy? ›

When enabled, a refresh token will expire based on an absolute lifetime, after which the token can no longer be used. If rotation is enabled, an expiration lifetime must be set. The Absolute Expiration of the rotating refresh token is defined on creation and is not changed, even with an exchange.

What is the best practice for JWT expiration time? ›

JWTs are self-contained, by-value tokens and it is very hard to revoke them, once issued and delivered to the recipient. Because of that, you should use as short an expiration time for your tokens as possible. A best practice is to set your JWT expiration to minutes or hours at maximum.

How do you handle token expiry? ›

To handle token expiration gracefully, the authentication function in the client library for each platform (JavaScript, Objetive-C, Java) allows us to set a cancel callback that is triggered when a token expires.

What is the max inactive time for refresh token? ›

Refresh and session token lifetime policy properties

Non-persistent session tokens have a Max Inactive Time of 24 hours whereas persistent session tokens have a Max Inactive Time of 90 days.

Top Articles
What Is Contrarian Investing? - Meaning, Examples & Strategies!
This simple formula tells you how long it will take for your money to double—while you sit back and relax
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 5664

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.