eMan_8888
eMan_8888

Reputation: 105

JWT refresh token practice

I'm trying to implement a refresh token concept on my website.

if I understand correctly the refresh token should be a unique identifier for a user to get a new token (the token is valid for 15min only).

I'm using customId package to generate a refresh token for each user on login.

when the token expires. I send a request to an endpoint to generate a new token based on the refresh_token provided for each user.

I'm using nuxt auth module.

try {
    const tokenUser = await User.findOne({
      refresh: req.body.refresh_token
    })
    // console.log(tokenUser)
    const newToken = await jwtr.sign({
      iu: tokenUser._id.toString()
    },
      'SUPERSECERT', {
      expiresIn: '5000' // Testing
    }
    );
 
    return res.json({
      token: newToken
    });

  } catch (e) {
    return res.status(401).send('unauthorized');
  }


Am I doing this correctly ? or should I store a newly created jwt token in refresh_token instead of a random unique string? Or did i miss something about the refresh tokens?

Upvotes: 1

Views: 569

Answers (1)

Michal Trojanowski
Michal Trojanowski

Reputation: 12342

This implementation is ok, though you may think of using something which is called a "rolling refresh token". Every time you use the refresh token to get a new access token, you also generate a new refresh token and return both to the client. From now on it should be only possible to get a new access token using the new refresh token. It gives you a bit more security in case someone manages to steal a refresh token.

Nevertheless, you should always expire your refresh tokens at some point (e.g. after a few hours). This will help you ensure that even if someone finds an old refresh token, they will not be able to use it. Once the refresh token expires you should ask the user to log in again.

Upvotes: 1

Related Questions