I am making API Server with Node.js and Express.
Also I used JWT token authentication for auth user.
If token is expired, my scenario is here.
(Backend) Middleware detect expired
(Frontend) Receive token is expired
(Fronend) Refresh token request to backend
(Backend) Verify token is valid and if it expired, sign new token(with old token's payload) and response it to frontend
at number 4, my code is here.
try {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, SECRET, (err, decoded) => {
if(err.name === 'TokenExpiredError') {
const payload = jwt.verify(token, SECRET);
const userid = payload.userid;
const is_admin = payload.is_admin;
const refreshToken = jwt.sign({
userid: userid,
is_admin: is_admin
}, SECRET, {
algorithm: 'HS256',
expiresIn: '10m'
})
res.status(200).json({status: true, token: refreshToken});
}
else if(err) {
res.status(401).json({status: false, result: "Invalid token"});
}
})
} catch(e) {
//console.log(e);
res.status(401).json({status: false, result: "Token does not exist"});
}
After run it, throw errors line of const payload = jwt.verify(token, SECRET);
.
Because if token is expired, it throws TokenExpiredError
error.
I want to decode token and extract payload of expired token.
But in verify()
, there is no information about payload.
So I read document, found some interest method decode()
.
But it mention that do not use decode()
, because it doesn't check signature is correct or not.
Is there any solution about extract payload of expired token?
Thanks.
You can set the option ignoreExpiration
to true to avoid getting this error for expired tokens (at that point you know it already) and then get the payload:
if(err.name === 'TokenExpiredError') {
const payload = jwt.verify(token, SECRET, {ignoreExpiration: true} );
// your code
}
Now you can be sure the token is valid but just expired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With