【问题标题】:Passport js is not working after cookie lifetime expiredcookie 生存期过期后 Passport js 不起作用
【发布时间】:2018-10-15 09:33:14
【问题描述】:

最近我在我的 express js 项目中发现了一个棘手的错误,我将不胜感激调试它。

这是相关的question,但答案不能解决问题,因为我想指定maxAge,从会话配置中删除这个参数对我来说不是解决方案。

我正在使用 Passport js + express-session

这是我的会话配置:

var passport = require('passport');
var session = require('express-session');
var cookieParser = require('cookie-parser');

app.use(cookieParser());

app.use(session({
    secret: 'MySecret',
    resave: false,
    saveUninitialized: false,
    cookie  : {
        secure: false, // If it's true, login is not working as well
        maxAge: new Date(Date.now() + (60 * 1000 * 30))    
    }
}));

app.use(passport.initialize());
app.use(passport.session());

为了检查用户是否经过身份验证,我使用了简单的中间件:

middlewareObj.isLoggedIn = function(req, res, next) {
    if (req.isAuthenticated()){
        return next();
    } else {
        return res.redirect('/signin');
    }
};

护照本地登录:

passport.use('local-signin', new LocalStrategy(
        {
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback: true
        },
        function (req, email, password, done) {
            var User = user;

            var isValidPassword = function (userpass, password) {
                return bCrypt.compareSync(password, userpass);
            }

            User.findOne({
                where: {
                    email: email
                }        
            }).then(function (user) {
                if (!user) {
                    return done(null, false, req.flash('error', 'User does not exists'));
            }

            if (!isValidPassword(user.dataValues.userPassword, password)) {
                return done(null, false, req.flash('error', 'Incorrect password.'));
            }

            return done(null, {user});

        }).catch(function (error) {
           return done(null, false, req.flash('error',error.message));
        });
    }
));

这是我的登出路线:

router.get('/logout',(req,res) => {
    req.session.destroy(function(err) {
        return res.redirect('/');
    });
});

标准用户登录工作正常,提交登录表单后用户为serialized 而不是deserializedisAuthenticated() 方法返回true

但是 cookie 配置(确切地说是maxAge)会产生一些问题。当 cookie 生存期到期时,下一个用户的登录将不再有效。 isAuthenticated() 方法正在返回 falsereq 中不存在用户对象)。

重启服务器后,用户可以正常登录,但是当cookie达到maxAge时,下一次登录就无法再次登录了。护照没有显示任何错误。

【问题讨论】:

    标签: node.js express cookies passport.js express-session


    【解决方案1】:

    这可能与您的 maxAge 值有关。 expressjs/sessions package docs 指出 maxAge 是“计算 Expires Set-Cookie 属性时使用的数字(以毫秒为单位)”。

    您将Date 传递给maxAge;它预计 cookie 过期前的毫秒数。

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 2013-02-07
      • 1970-01-01
      • 2020-04-14
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2017-11-10
      相关资源
      最近更新 更多