护照无法保持持久的登录会话

5
我先看了一下使用Passport、MongoDB和Express实现持久化会话,但是它没有帮助或者说不太合理。
我正在尝试让我的网站实现持久登录。我的序列化过程出了问题。
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
    console.log('serializing user:',user.username);
    //return the unique id for the user
    return done(null, user._id);
});

//Desieralize user will call with the unique id provided by serializeuser
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        console.log('deserializing user:',user.username);
        return done(err, user);
    });
});

整个护照文件可以在github上找到。
我认为问题在于我立即反序列化,或者至少控制台日志显示如此。
或者可能与我的会话有关:
app.use(session({
    secret: 'keyboard cat',
    cookie : {
        maxAge: 3600000 // see below
    }
}));

这是我的用户模式:

var userSchema = new mongoose.Schema({
    username : String,
    password : String, //Hash
    created_at : {type: Date, default : Date.now}
});

谢谢帮助!

3个回答

3
您所提到的链接 “使用passport,mongodb和express实现持久会话”,讨论的是一个旧版本的express框架,而您在package.json中使用的是非常新的版本,https://github.com/manu354/teecher/blob/master/package.json"express": "~4.13.1"
您需要将下面这些行移动:
app.use(passport.initialize());
app.use(passport.session());

app.use(session({...})的下方略微上面一点点。

我建议您阅读这篇博客文章:http://mherman.org/blog/2015/01/31/local-authentication-with-passport-and-express-4/,它肯定会帮助您。


2
您的问题不在护照或后端,而是在前端的Angular上。您仅在用户执行登录操作时设置 $rootScope.authenticated ,但您需要通过调用API在每个应用程序初始化时与服务器进行检查,以查看用户是否已经登录。

因此,也许在 routes / api.js 中创建一个 router.route('/ current_user')路由,它应该返回 null (或某种来宾用户对象),否则它将返回当前已登录的用户信息,以便您的前端Angular应用程序知道用户是否已登录并具有一些用户信息可以使用。如果/ api / current_user 提供了一个用户,则知道您已登录,然后可以设置 $rootScope.authenticated = true

抱歉,我刚刚才看到这个答案。我会去看一下!这似乎是解决办法。 - Manu Masson

0

只是为了帮助其他人而发布。

检查您的客户端/浏览器是否执行了Set-Cookie头。

在我的情况下,Safari可以正常工作,但Chrome或Firefox不能。显然是客户端问题,因为没有浏览器识别服务器端代码。 Safari和Chrome / Firefox之间的差异之一是,在Safari中使用了fetch polyfill,而Chrome和Firefox原生支持它。fetch不会使用Set-Cookie头,除非您在其选项中提供credentials


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接