18

I am using passport-jwt to generate my tokens but I noticed that the tokens never expire, is there any way to invalidate a particular token according to a rule set for me, something like:

'use strict';
const passport = require('passport');
const passportJWT = require('passport-jwt');
const ExtractJwt = passportJWT.ExtractJwt;
const Strategy = passportJWT.Strategy;
const jwt = require('../jwt');
const cfg = jwt.authSecret();

const params = {
    secretOrKey: cfg.jwtSecret,
    jwtFromRequest: ExtractJwt.fromAuthHeader()
};

module.exports = () => {
    const strategy = new Strategy(params, (payload, done) => {
        //TODO: Create a custom validate strategy
        done(null, payload);
    });
    passport.use(strategy);
    return {
        initialize: function() {
            return passport.initialize();
        },
        authenticate: function() {
            //TODO: Check if the token is in the expired list
            return passport.authenticate('jwt', cfg.jwtSession);
        }
    };
};

or some strategy to invalidate some tokens

1
  • Could you solve it?
    – Mr. B.
    Commented Feb 7, 2017 at 9:08

4 Answers 4

29

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 route
router.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).

4
  • What are the best practices to extend the lifetime of token? For example, if a user wants to spend more than 30 minutes in the application?
    – trojek
    Commented Aug 24, 2017 at 7:29
  • This is done through what's commonly referred to as a 'refresh token', which basically means you ask for a new auth token against a specific endpoint. The client application has to be proactive about this, usually. More details: auth0.com/blog/…
    – Paul
    Commented Aug 24, 2017 at 15:16
  • 1
    I added expiresIn: '10s' but doesn't work. Token is working after 10 seconds. Commented Jun 29, 2022 at 18:50
  • @iamcrypticcoder same, the token never expires
    – Jplus2
    Commented Aug 27, 2022 at 8:28
2

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}) 
0

If you want to manipulate expiresIn with seconds

const { sign } = require('jsonwebtoken');

function generateToken(id) {
  const options = {
    expiresIn: 10, // seconds
    algorithm: 'RS256'
  };
  const payload = {
    sub: id,
    iat: Math.floor(Date.now() / 1000)
  };
  return sign(payload, 'PRIVATE_KEY', options);
}
-5

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.

3
  • 9
    If you're still doing that I would suggest to stop. You're missing the whole point of JWTs as they should be stateless. Commented May 5, 2017 at 8:58
  • 2
    Yeah exactly, bad practice here. Better alternatives for a stateful approach. Commented Nov 30, 2017 at 1:49
  • As stated previously, JWT are stateless and should not be stored in the database
    – stefano
    Commented Dec 7, 2020 at 18:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.