3
votes

I'm working on a SPA app based on Node, with token-based authentication using JWT. Right now, the jwt token never expires, which is not good.

I want it to expire for more security, but I don't want my users to be forced to re-log. That's why I need a refresh token.

So i'm reading about OAuth2. I have a hard-time to understand why refresh-tokens must be stored in a database, whereas access-token are generated on the fly using a secret key. Why refresh tokens can't be generated the same way as access tokens ?

Thank you guys !

1

1 Answers

2
votes

Refresh tokens usually are generated the same way as access tokens. An authorization server will often return a refresh and access token if requested (and you're not using the implicit grant type).

The difference is how they are used.

An access-token is usually a bearer token: whoever has it can use it against the resource server, but it is only valid for a short period of time. In which case, storing them in a database is often pointless as they are worthless once expired.

A refresh token however is like having access to a "forge" which allows you to mint a new token.

If you present the refresh token to the authorisation server (not the resource server) you will get back a new access token and possibly a new refresh token. Providing of course that the user has not revoked/changed access permissions to your application and that the user is still a valid user.

So you would keep them in a database perhaps because your user logs in infrequently. So you may need the refresh token weeks after you got it.

Alternative to the refresh token.

If you are using the implicit grant (which is common with SPAs but not recommended). You can try and keep your end user logged in to the identity provider used by the authorisation server. This way you can keep requesting new access tokens from the auth server without the user being prompted by the auth server for credentials as a session will be persisted between the identity provider and the user's browser.