Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract payload of expired jwt token

Tags:

node.js

jwt

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.

  1. (Backend) Middleware detect expired

  2. (Frontend) Receive token is expired

  3. (Fronend) Refresh token request to backend

  4. (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.

like image 312
Hide Avatar asked Jul 11 '18 08:07

Hide


1 Answers

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.

like image 62
jps Avatar answered Oct 10 '22 16:10

jps