How can you verify if a JWT is still valid?
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);
Related videos on Youtube
Christopher Mellor
Updated on October 03, 2022Comments
-
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 over 5 yearsI wouldn't do that at a set time interval - it should rather be done on every request that needs auth.
-
-
Yosi Leibman about 4 yearsif the user refreshes the page, the timer stops and the token will be stored forever, how do I solve this?
-
Yosi Leibman about 4 yearsand call this function every few seconds using setInterval or so? this is not a performance issue?
-
Dupocas about 4 yearsUsually 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 almost 4 yearsPeople 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 almost 4 yearsyou use it in HOC same way you check your store for authentication status.