Passport-jwt令牌过期
我正在使用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); } }; };
或一些策略来使一些令牌无效
JWT的标准是将有效载荷中的有效期限作为“exp”。 如果你这样做了,除非你明确告诉它,否则护照-JWT模块将会尊重它。 比自己实施更容易。
编辑
现在有更多的代码!
我通常使用npm模块jsonwebtoken
实际创build/签署我的令牌,它有一个选项,用于在有效负载的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 }); });
您的JWT策略可以看起来像您所看到的,而且会自动遵守我上面设置的30分钟(显然,您可以设置其他时间)的到期时间。
我在数据库中创build了一个存储生成的令牌的文档,并在用户发出请求时检查令牌是否过期或添加了过期date。
这是我使用的validation策略。
/* ----------------------------- 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); /* -------------------------------------------------------------------------------*/
这对我有用。