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

查看:41
本文介绍了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 不会返回到浏览器,并且一切都会以静默方式失败.删除此标志为我解决了这个问题 - 花了几个小时才意识到这一点!

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天全站免登陆