Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expire token in jwt-simple?

I just implemented jwt-simple,on my backend in nodejs.i want to expire token by given time.

 var jwt = require('jwt-simple');
    Schema.statics.encode = (data) => {
    return JWT.encode(data, CONSTANT.ADMIN_TOKEN_SECRET, 'HS256');
};
Schema.statics.decode = (data) => {
    return JWT.decode(data, CONSTANT.ADMIN_TOKEN_SECRET);
};

how to add expires time in jwt-simple

like image 768
coder Avatar asked Mar 10 '23 21:03

coder


2 Answers

There is no default exp. Two ways you can add it mannually:

  1. With plain js:

    iat: Math.round(Date.now() / 1000), exp: Math.round(Date.now() / 1000 + 5 * 60 * 60)

  2. With moment.js:

    iat: moment().unix(), exp: moment().add(5, 'hours').unix()

Source from original Github repository.

like image 168
Stanley Luo Avatar answered Mar 20 '23 03:03

Stanley Luo


You can validate your token with a expirate date in the passport Strategy function, like this:

passport.use(new JwtStrategy(opts, function(jwt_payload, done){
    User.find({id: jwt_payload.id}, function(err, user){
        if (err) {
            return done(err, false, {message: "Incorrect Token!!"});
        }
        if (user) {
            if (user[0].token_expiration_date <= Date.now()){
                return done(null, false, {message: "Expired Token"});
            }else{
                return done(null, user);
            }
        }else{
            return done(null, false, {message: "Incorrect Token"});
        }

    });
}));

Hope that this can help you.

like image 22
David Alexander Linares Villam Avatar answered Mar 20 '23 01:03

David Alexander Linares Villam