Passport-jwt令牌到期 [英] Passport-jwt token expiration

查看:396
本文介绍了Passport-jwt令牌到期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

JWT的标准是将有效期中的到期时间包括为"exp".如果这样做,除非您明确指示不这样做,否则passport-JWT模块将尊重它.比自己实施更容易.

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.

编辑

现在有更多代码!

我通常使用npm模块jsonwebtoken实际创建/签名我的令牌,该模块具有使用有效载荷的exp元素中的友好时间偏移量来设置到期时间的选项.它的工作原理如下:

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

从我的角度来看,您的JWT策略可以看起来像您已经拥有的那样,并且它将自动遵守我在上面设置的30分钟的过期时间(显然,您可以设置其他时间).

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

这篇关于Passport-jwt令牌到期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆