Passport-jwt令牌到期

1fa*_*ira 6 node.js express jwt passport.js

我使用passport-jwt来生成我的令牌,但是我注意到令牌永不过期,是否有任何方法可以根据为我设置的规则使特定令牌无效,例如:

'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);
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

或一些使一些令牌无效的策略

Pau*_*aul 10

JWT的标准是将有效载荷中的到期时间包括为"exp".如果你这样做,护照-JWT模块将尊重它,除非你明确告诉它.比自己实现它更容易.

编辑

现在有更多的代码!

我通常使用npm模块jsonwebtoken实际创建/签署我的令牌,它有一个选项,用于在有效负载的exp元素中使用友好时间偏移设置到期.它的工作原理如下:

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 });
});
Run Code Online (Sandbox Code Playgroud)

从我看来,你的JWT策略看起来就像你已经拥有的那样,它将自动尊重我在上面设置的30分钟的到期时间(显然,你可以设置其他时间).