我正在尝试使用node.js,express和passport.js建立登录机制.登录本身工作得非常好,会话与redis很好地存储,但是在提示进行身份验证之前,我确实遇到了将用户重定向到他开始的地方的麻烦.
例如,用户跟随链接http://localhost:3000/hidden然后被重定向到http://localhost:3000/login但我希望他再次被重定向回http://localhost:3000/hidden.
这样做的目的是,如果用户随机访问他需要首先登录的页面,他将被重定向到提供其凭据的/ login站点,然后被重定向回他之前尝试访问的站点.
这是我的登录帖子
app.post('/login', function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
if (err) {
return next(err)
} else if (!user) {
console.log('message: ' + info.message);
return res.redirect('/login')
} else {
req.logIn(user, function (err) {
if (err) {
return next(err);
}
return next(); // <-? Is this line right?
});
}
})(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)
在这里我的ensureAuthenticated方法
function ensureAuthenticated (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login'); …Run Code Online (Sandbox Code Playgroud)