How can you verify if a JWT is still valid?

14,977

Solution 1

An elegant solution to handle token expiration is when you set the token(in LocalStorage or store(redux), or both) is also to have an Async function that runs exactly when the token expires. Something like this:

const logUserOut = token =>{
    setTimeout(()=> MyLogoutFunction(), token.expiresIn)
}

This way you make sure that the user won't be logged when the token is no longer valid.

Solution 2

You can have your client side decode the JWT and check an expiry field and compare it with system time.

eg.

  isExpired: (token) => {
    if (token && jwt.decode(token)) {
      const expiry = jwt.decode(token).exp;
      const now = new Date();
      return now.getTime() > expiry * 1000;
    }
    return false;

you can use npm install jsonwebtoken or some other npm package on the client side to do this

Solution 3

Create and endpoint that verifies the token is valid. You can use the the jsonwebtoken package.

import jwt from 'jsonwebtoken';

const verifyToken = (req, res) => {
  const token = req.headers.authorization;
  jwt.verify(token, SECRET_KEY, (err, decoded) => {
    if (err) {
      return res.status(401).send();
    }
    // can do something with the decoded data
  })
}

router.post('/verify-token', verifyToken);
Share:
14,977

Related videos on Youtube

Christopher Mellor
Author by

Christopher Mellor

Updated on October 03, 2022

Comments

  • Christopher Mellor
    Christopher Mellor over 1 year

    I want to make a call every X amount of minutes from the client side to see if the JWT is still valid. I'm not sure how to do this in nodeJS. If I'm already authorized, how can i check if I'm still authorized.

    • Kamil Solecki
      Kamil Solecki over 5 years
      I wouldn't do that at a set time interval - it should rather be done on every request that needs auth.
  • Yosi Leibman
    Yosi Leibman about 4 years
    if the user refreshes the page, the timer stops and the token will be stored forever, how do I solve this?
  • Yosi Leibman
    Yosi Leibman about 4 years
    and call this function every few seconds using setInterval or so? this is not a performance issue?
  • Dupocas
    Dupocas about 4 years
    Usually this is done server side, and every time the users starts the application (by refreshing or opening for the first time) a request of validation is sended from the client to verify the JWT's validity.
  • Someone Special
    Someone Special almost 4 years
    People who are reading this, if you use HMAC algorithm you should not be using the above code on the client side. You should not reveal your key publicly.
  • Someone Special
    Someone Special almost 4 years
    you use it in HOC same way you check your store for authentication status.