Search code examples
authenticationoauthoauth-2.0basic-authentication

How to refresh token without getting having to go through auth again? OAuth2


How to refresh the access token without having to go through the authentication process again with OAuth2??

Right now if fetch user fails, I will do refresh token, but in order to do refresh token I must first receive a 401 unauthorized error.

By the time I receive the 401 after not being able to do a request, i redirect to the login screen because if i dont redirect to the login screen, the subsequent requests will just not show up.

IF i used an expiration time, the token wouldn't refresh without first doing a request, but by the time the request is made the token had already expired.

What i am asking is what is the logic that i should use for refreshing access tokens so my app won't log out everytime the token expires and require another authentication.

I would like my app to function more like facebook or google where you stay logged in until you log out.

Thanks in advance.


Solution

  • Could you let me know what type of app and tech stack you are using?

    There are two times:

    • Access token lifetime - a short lived API credential (eg 60 minutes)

    • User session lifetime (usually represented by a refresh token - eg 12 hours)

    There are mechanisms to silently renew tokens client side. The general approach is to get a new token and retry the API call when you get a 401 due to access token expired, as in this class of mine.

    How you get a new token depends on the type of app (mobile / SPA / cookie based web app)