我正在尝试使用node.js,express和passport.js建立登录机制。登录本身运行良好,也在redis中很好地存储了会话,但我在重定向用户到进行身份验证之前所在的位置时遇到了一些问题。
例如,用户访问链接http://localhost:3000/hidden
,然后被重定向到http://localhost:3000/login
,但我希望他再次被重定向回http://localhost:3000/hidden
。
这样做的目的是,如果用户随机访问页面,需要先登录,他将被重定向到登录页面提供凭据,然后再被重定向回他之前尝试访问的网站。
这是我的登录提交代码:
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);
});
这里是我的 ensureAuthenticated 方法
function ensureAuthenticated (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
该钩子连接到/hidden
页面
app.get('/hidden', ensureAuthenticated, function(req, res){
res.render('hidden', { title: 'hidden page' });
});
登录页面的HTML输出非常简单。
<form method="post" action="/login">
<div id="username">
<label>Username:</label>
<input type="text" value="bob" name="username">
</div>
<div id="password">
<label>Password:</label>
<input type="password" value="secret" name="password">
</div>
<div id="info"></div>
<div id="submit">
<input type="submit" value="submit">
</div>
</form>