Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is refresh token is more secure & why do we use refresh token if it can also be stolen?

Suppose my user logged in and I gave him 2 tokens ; access and refresh token

access token is valid for 15 minutes and refresh token is valid for 1 week

We don't want to give them only access token valid for a long period since someone can obtain that access token and make requests with it, that's why we are making it valid for 15 minutes.

However, can't our refresh token also be stolen ? Someone can obtain our refresh token and gets an access for 1 week ? So why do we give two different tokens and implement access-refresh based token authentication if both of them are subject to danger ?

like image 911
normativepcoder Avatar asked Sep 12 '25 11:09

normativepcoder


2 Answers

You're somewhat right :) and it depends on the properties of the application you use. For example, if you have a public client (e.g. an SPA running in the browser), and you give that client access to both access and refresh tokens then you indeed lose the added security the refresh token normally would give you. If the public client can refresh tokens then anyone who steals your refresh token can use it to create new access tokens. That's why SPAs usually are not given refresh tokens directly - these tokens are either kept in an http-only cookie, or the SPA would use an SSO session to refresh the access token (then no refresh token is used).

In a confidential client we can use refresh tokens more securely, as they can't be stolen that easily, and even if stolen, the attacker would also have access to the client's secret to authenticate at the refresh endpoint.

What @luk2302 said in his comment also depends on the implementation. You can have servers where it's possible to revoke both access and refresh tokens, and also servers which can't revoke refresh tokens (it's not a requirement of the OAuth RFC).

like image 65
Michal Trojanowski Avatar answered Sep 14 '25 05:09

Michal Trojanowski


Based on Sascha Preibisch's video on YT there are 2 ways the refresh token can be implemented.

  • With a sliding window
  • Or with a fixed lifetime

To me the sliding window makes more sense.

Then lifetime of the refresh token should be similar to the access token (minutes or hours). And the token will just be used for as long as the user is being active instead of hours or days after activity ends.

A long lived refresh token always seems like bad news to me.

enter image description here

Essentially the refresh token should be so that you don't need to log in twice when spending e.g. over 1hr on a website / API.

like image 25
Paku Avatar answered Sep 14 '25 05:09

Paku