【问题标题】:Passport deserialize function is removing user from the sessionPassport 反序列化功能正在从会话中删除用户
【发布时间】:2016-04-10 06:06:26
【问题描述】:

坦率地说,我今天才开始学习护照。我觉得我了解护照的一些工作原理,但我仍在努力熟悉自己。我的问题(我认为)是我的用户被从会话中删除,这阻止了我到达经过身份验证的路由。我在反序列化函数中 console.logged 用户 id 以检查它是否存储在会话中,它是...

  //serialize user into the session
passport.serializeUser(function(user,done){
   done(null,user.id); 
});

//deserialize the user from the session
passport.deserializeUser(function(id,done){

    console.log('user id is: ' + id); //works and logs user id

    User.findById(id, function(err,user){
       done(err,user); 
    });
});

这是我的路线和护照中间件...

app.post('/login', function(req,res,next){
    passport.authenticate('local-login', function(err,user,info){
       if(err){
           console.log("we have an internal error!");
           return next(err);
       }
       if(!user){
           return res.send({success:false, message:'failed to login!'});
       }else{
           req.login(user, function(err){
                if(err){
                    return next(err);
                }
                    return res.send({ success : true, message : 'authentication succeeded' }); 
            });
       }

    })(req,res,next);
}); 

//route middleware to make sure that a user is logged in 

    function isLoggedIn(req,res,next){

     //if the user is authenticated in the session, carry on
         if(req.isAuthenticated()){
               next();
         }

    //if they are not authenticated in the session, redirect them to the home page
         res.redirect('/');
    }

非常感谢任何帮助、见解和建议;谢谢!

【问题讨论】:

  • 我认为你的问题是如果req.isAuthenticated(),你需要在isLoggedIn 中使用return。现在你先做next(),然后再做res.redirect('/');。并且没有检查数据库并且知道 确定会话已经消失 - 不要做出这样的假设 :)
  • 是的,我只是想对可能出现的问题提出一个想法......现在已经有一段时间了:/。你说在 isLogged() 函数中放一个 return,但我不需要 next() 来逃避中间件边缘吗?
  • 是的,但是调用 next 并不会阻止函数继续执行。所以你现在调用both next AND res.redirect。在调用 next 后返回 :) 像 next(); return; 甚至 return next();
  • 我真的很感激 Andrey,这就是解决方案 :) 。一切终于奏效了!我一直认为 next() 也起到了回报的作用。

标签: node.js express session-cookies passport.js


【解决方案1】:

这是因为您总是将用户重定向到您的 isLoggedIn 中间件中的索引页面。需要使用return:

function isLoggedIn(req,res,next){
     if(req.isAuthenticated()){
           next();
           // STOPS further execution of this function and prevents redirecting the user
           return;
     }
     res.redirect('/');
}

请记住,它只是 JavaScript - 没有框架做任何更改 - Express、Passport 甚至 Promises 都是纯 JS,它们不会修改虚拟机的工作方式。 GL!

附言 如果出现问题,尤其是在开始时,我建议使用if-else 语句。这样你就不会有问题了:

if (req.isAuthenticated()) {
    next();
} else {
    res.redirect('/');
}

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 2017-11-05
    • 2018-03-30
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 2021-08-26
    • 2021-06-05
    相关资源
    最近更新 更多