JWT refresh token strategy

Viewed 3286

I see in a blog (here) about Authentication in React with JWT, this setup: access token expiry is 15 minutes , refresh token expiry is 1 month; every 10 minutes the client calls the /refreshToken endpoint, to check if refreshToken is still valid (otherwise the user is shown the login screen).

On the server, the /refreshToken endpoint correctly checks that the refreshtoken is not expired, that the user with the id in refreshtoken payload is still existing and valid (i.e.: the passed refreshToken is present in his refreshTokens array). If everything's fine, a new access token is generated, and sent back with the response.

So far so good. But, before returning the response, a new refreshToken is generated, too, and replaced to the old one into users's refreshTokens array... I think this strategy is flawed, since this way the user will never see his login to expire, even after refresh token (one month in this example) will be overdue...

I did make some tests (lowering the 1 month value to 30 minutes), and effectively the user authorization never expires... Forcing a logout of the user deleting his refreshTokens array obviously works fine, but I'd expect a logout when the refresh token expires by age.

I ask if my understanding is correct (the refreshToken endpoint on the server should not refresh the refresh token, but the access token only), or if I miss something.

UPDATE after @Ghero comment: I see your point... But why to refresh a token if not to update it's expiry?
However, the blog's code used to renew the refresh token:

    const jwt = require("jsonwebtoken");

    exports.getRefreshToken = (user) => {
      const refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, {
        expiresIn: eval(process.env.REFRESH_TOKEN_EXPIRY),
      });
      return refreshToken;
    };

    // REFRESH_TOKEN_EXPIRY is set to 30 days

It looks like it is always postponing the expiry date 30 days in the future. This way it will never expire...

1 Answers

Having the refresh token being replaced on each use is a current best practice.

Having a one-time use refresh token means that if the refresh token is stolen and used more than once (by you and the hacker), the token service can then detect that and sign-out the user automatically, protecting the user from attacks.

There is a max time that the refresh token is valid, for example 30 days, but that is also often something that you can configure. There are different refresh token lifetime strategies, depending on the service that you use. The picture below shows how IdentityServer deals with refresh tokens: enter image description here

Related