PassportJS deserializeUser从未调用 [英] PassportJS deserializeUser never called

查看:211
本文介绍了PassportJS deserializeUser从未调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了Passport来对存储在mongodb中的用户进行身份验证.似乎可以正常工作:身份验证成功/失败,并且设置了会话变量.但是,让Passport检查会话失败.我添加到deserializeUser回调中的console.log语句似乎从来没有出现过错,这似乎是很错误的.我认为我的问题与从未调用过的deserializeUser有关.有人能够诊断出我的失误吗?

I've got Passport setup to authenticate users stored in mongodb. Seems to work fine: authentication succeeds/fails appropriately and session variables get set. However, getting Passport to check for a session is failing. Something seems to be quite wrong in that the console.log statements I've added to the deserializeUser callback never see the light of day. I assume my problem is related to deserializeUser never being called. Anyone able to diagnose my misstep?

// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user.id) });
passport.deserializeUser(function(uid, cb){
  console.log("Trying to deserialize user: "+uid);
  User.findById(uid, function(err, user){
    cb(err, user);
  });
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
  function(email, pass, done){
    User.findOne({email: email}, function (err, user) {
      if (err)
        return done(err);
      if (!user)
        return done(null, false, {message: "Couldn't find user"});
      var crypted = bcrypt.hashSync(pass, user.salt);
      if(user.hashpass != crypted)
        return done(null, false, {message: "Bad password"});
      return done(null, user);
    });
  }
));

passport.CreateSession =  function (req, res, next) {
  passport.authenticate('local', function(err, user, info){
    if(err || !user)
      return res.json({status: "Failure: "+err});
    req.logIn(user, function (err){
      if(err)
        return res.json({status: "Failure: "+err});
      return res.json({status: "Authenticated"});
    });
  })(req, res, next);
};

在app.js中具有以下内容:

with the following in app.js:

app.post('/session', passport.CreateSession); // restify better
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, routes.images);

推荐答案

对于其他遇到此问题的人,请查看以下内容:

For anyone else who is having this issue, take a look at this:

app.use(session({ 
    secret: 'something', 
    cookie: { 
        secure: true
    }}));

如果您将cookie.secure设置为true,并且没有使用SSL(即https协议),则会话ID为cookie的cookie不会返回到浏览器,并且所有操作都会静默失败.删除该标志对我来说解决了问题-花了数小时才意识到这一点!

If you have cookie.secure set to true and you're NOT using SSL (i.e. https protocol) then the cookie with the session id is not returned to the browser and everything fails silently. Removing this flag resolved the problem for me - it took hours to realise this!

这篇关于PassportJS deserializeUser从未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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