Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you verify if a JWT is still valid?

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.

like image 767
Christopher Mellor Avatar asked Sep 12 '18 22:09

Christopher Mellor


3 Answers

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

like image 103
izb Avatar answered Nov 15 '22 22:11

izb


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.

like image 25
Dupocas Avatar answered Nov 15 '22 23:11

Dupocas


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);
like image 44
pizzarob Avatar answered Nov 15 '22 22:11

pizzarob