Reputation: 304
how to check whether my token is expired or not?
var token = jwt.sign(user,app.get('superSecret'),{
expiresIn : 2
});
Upvotes: 10
Views: 71992
Reputation: 2395
This is method works for me.
If you set an expiry date on the signed token. JWT will validate it for you.
Sign a token.
try {
const token = jwt.sign({ uuid: '123456' }, JWT_SECRET, { expiresIn: '1min' })
return token
} catch (error: unknown) {
if (error instanceof jwt.JsonWebTokenError) {
return error.message
}
}
Verify
try {
const token = ''
const decoded = jwt.verify(token, JWT_SECRET)
return decoded
} catch (error: unknown) {
if (error instanceof jwt.JsonWebTokenError) {
return error.message
}
}
After 1 minute(expiresIn: '1min'
), then the token will become invalid.
Upvotes: 0
Reputation: 97
You have to add an error instance
const decoded = verify(token, process.env.TOKEN_KEY || '', (err: any, decoded: any) => {
if (err instanceof TokenExpiredError) {
return res.status(401).send({ success: false, message: 'Unauthorized! Access Token was expired!' });
}
if (err instanceof NotBeforeError) {
return res.status(401).send({ success: false, message: 'jwt not active' });
}
if (err instanceof JsonWebTokenError) {
return res.status(401).send({ success: false, message: 'jwt malformed' });
}
});
Upvotes: 0
Reputation: 71
The best way set the code in your parent component of page or wrapper. Your need delete your old (expared) token.
let token = localStorage.getItem( 'token' );
jwt.verify( token, 'yourkey', function(err, decoded) {
if ( err ) {
localStorage.removeItem( 'token' );
}
} );
Upvotes: 0
Reputation: 1
You need set the host current time to compare the expiration date in the verify function example:
jwt.verify(token, JWT.SECRET_KEY, {clockTimestamp: new Date().getTime()}, callback)
the clockTimestamp property is required to set the host current time.
Upvotes: 0
Reputation: 2509
I assume you are using the jsonwebtoken package that is documented here
If that is the case, have a look at the jwt.verify
method:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
In short words: Check the error of that method. If it is the TokenExpiredError then, guess what... the token is expired.
Upvotes: 27
Reputation: 580
var isExpiredToken = false;
var seconds = 1000;
var d = new Date();
var t= d.getTime();
if (decoded.exp < Math.round(t / seconds)) {
// code...
isExpiredToken = true;
}
Source: https://www.w3schools.com/jsref/jsref_gettime.asp
Upvotes: 0
Reputation: 467
var isExpiredToken = false;
var dateNow = new Date();
if(decodedToken.exp < dateNow.getTime()/1000)
{
isExpiredToken = true;
}
Upvotes: 18
Reputation: 87
var isExpiredToken = false;
var dateNow = new Date();
if(decodedToken.exp < dateNow.getTime())
{
isExpiredToken = true;
}
Upvotes: 7