为什么即使策略通过,req.isAuthenticated()还是错误的

时间:2019-02-04 21:33:26

标签: express passport.js

我有以下简单的LocalStrategy ...

passport.use(new LocalStrategy(
    function(username, password, done){
        console.log(`Checking the user and password`);
        if(username === "user" && password === "password"){
            console.log("Correct!");
            return done(null, true);
        }
        return done(null, false);
    }
));
passport.serializeUser(function(user, done) {
    console.log(`User is ${user}`);
    done(null, user);
});
passport.deserializeUser(function(user, done) {
    console.log(`Deserialize User is ${user}`);
    done(null, user);
});

然后我有以下中间件。...

const checkAuth = (req, res, next) =>{
    console.log(`Passport is ${JSON.stringify(req.session.passport)}`);
    console.log(`Is Auth ${req.isAuthenticated()}`);
    if(req.path === '/login' || req.isAuthenticated()){
        console.log("Authenticated");
        return next();
    }
    res.redirect('/login');
};
...
this.express.use(checkAuth);

运行此命令并使用user password登录时,我得到以下信息...

Passport is undefined
Is Auth false
Authenticated

这是要登录的POST,因此无论它看起来如何都被认为已通过身份验证,但是,此后,我们看到密码已检查并且正确,但是会话仍未定义护照对象,因此它重定向回登录...

Checking the user and password
Correct!
Passport is undefined
Is Auth false
...

返回后,会话似乎没有任何保存到...

{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"}}

这是我设置会话的方式...

    this.express.use(session({
        secret: 'keyboard cat',
        saveUninitialized: true,
        resave: true
    }));
    this.express.use(passport.initialize());
    this.express.use(passport.session());

为什么认证失败,如何正确设置?

0 个答案:

没有答案