我正在尝试使用 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);
});
这里是我的 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>