我正在try 使用node建立登录机制.js,express 和Passport .js.登录本身工作得很好,而且会话在redis中也存储得很好,但在提示用户进行身份验证之前,我确实在将用户重定向到起始位置时遇到了一些问题.
e、 g.用户跟踪链接http://localhost:3000/hidden
然后被重定向到http://localhost:3000/login
,但我希望他再次被重定向回http://localhost:3000/hidden
.
这样做的目的是,如果用户随机访问他需要首先登录的页面,他将被重定向到提供其凭据的/login站点,然后被重定向回他之前try 访问的站点.
这是我的登录帖子
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);
});
这里是我的确认方法
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>