首页 > 解决方案 > 即使策略通过,为什么 req.isAuthenticated() 为假

问题描述

我有以下简单的 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());

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

标签: expresspassport.js

解决方案


推荐阅读