Passport-jwt token expiration Passport-jwt token expiration express express

Passport-jwt token expiration


The standard for JWT is to include the expiry in the payload as "exp". If you do that, the passport-JWT module will respect it unless you explicitly tell it not to. Easier than implementing it yourself.

EDIT

Now with more code!

I typically use the npm module jsonwebtoken for actually creating/signing my tokens, which has an option for setting expiration using friendly time offsets in the exp element of the payload. It works like so:

const jwt = require('jsonwebtoken');// in your login routerouter.post('/login', (req, res) => {  // do whatever you do to handle authentication, then issue the token:  const token = jwt.sign(req.user, 's00perS3kritCode', { expiresIn: '30m' });  res.send({ token });});

Your JWT Strategy can then look like what you have already, from what I see, and it will automatically respect the expiration time of 30 minutes that I set above (obviously , you can set other times).


You can use the following strategy to generate JWT-token with expiration limit of 1 hr.

let token = jwt.sign({    exp: Math.floor(Date.now() / 1000) + (60 * 60),    data: JSON.stringify(user_object)}, 'secret_key');res.send({token : 'JWT '+token}) 


I created a document in the database that stores the generated tokens and added an expiration date, when the user makes the request check if the token is expired or no.

This is verify strategy that I used.

/* ----------------------------- Create a new Strategy -------------------------*/const strategy = new Strategy(params, (payload, done) => {    const query = {        token: jwtSimple.encode(payload, credentials.jwtSecret),        expires: {$gt: new Date()}    };    TokenSchema.findOne(query, (err, result) => {        if (err) done(err, null);        if (!result) done(null, null);        done(null, payload);    });});passport.use(strategy);/* -------------------------------------------------------------------------------*/

It's work for me.