Sam Leurs
Sam Leurs

Reputation: 2020

Best practice using JWT refresh token in nodejs

I'm using JSON Web Tokens for authentication in my react-native app. When a user signs in, a token is created and send to the user to store in the local storage. The token is valid for 24 hours. Whenever the server (nodejs) is called, the token is send in a header.

The problem is, after 24 hours, the user has to sign in again. I don't want this, so I started searching for solutions. The solution I found: refresh tokens.

My approach so far. Please correct me if I'm doing something wrong.

1) A user signs in. An auth token and a refresh token are both send to the user to store in the local storage. (Is this safe enough?)

2) The user wants to change his profile. I send a request to the server with the auth token in a header.

3) The server receives the auth token. If the auth token is still valid, do whatever you have to do. If the auth token is expired, check if the user has a refresh token (that's still valid). At this point, I'm stuck. Should I send a new request from the server to the user with the question "do you have a refresh token?" and if so, send this refresh token to the server to create a new auth token?

The problem for me is the following:

Let's say the user wants to get the last 10 messages from a list. A request with the auth token is send to the server.

=> the auth token is valid: the response is a list of 10 messages

=> the auth token is invalid: the response is a new request from the server to the client for the refresh token

These are 2 different responses. Wouldn't that mess up my code at the client side? How should I handle this?

An alternative could be to send the auth token AND the refresh token in every request. But would that make sense?

Upvotes: 2

Views: 1595

Answers (1)

Shaun the Sheep
Shaun the Sheep

Reputation: 22762

Do you mean refresh tokens as in OAuth2? If so, these are usually only used with server clients (not browser apps). Using a refresh token requires client authentication in order to retrieve a new access token, which makes it different from just sending the access token to a resource (which usually gives access just by itself).

As such it's not clear that using refresh tokens adds anything here. If you think it's safe enough to keep people logged in to your app for more than 24 hours, why not just make the session last longer and extend the lifetime of the token you issue?

With respect to storage, keeping secure information in local storage is generally frowned on. If you are certain that you have no vulnerable external Javascript and you are using a very strict Content Security Policy header with your site to prevent any inline Javascript or undesired sources, and your app isn't super high risk, then it may be OK.

Upvotes: 0

Related Questions