5

我正在尝试使用 express 在 node.js 服务器上设置护照本地身份验证。看起来它应该非常直截了当。但我被卡住了。

这两个片段可以很好地协同工作:

app.get('/', ensureAuthenticated, function(req, res){
    res.redirect('/index.html', { user: req.user });
});

app.post('/login', 
    passport.authenticate('local', { failureRedirect: '/login.html', failureFlash: true, successFlash: "Success!" }),
    function(req, res) {
    res.redirect('/');
});

问题是没有什么能阻止我在地址栏中输入“www.myurl.com/index.html”并直接放到我的页面上。

如果我使用这样的任何代码:

app.get('/index.html', ensureAuthenticated, function(req, res){
    res.redirect('/index.html', { user: req.user });
});

似乎我陷入了一个循环......如果它可以检查我的身份验证并在我的路上发送我,而不是永远检查每个重定向,那就太好了。避免这种情况的方法是什么?

我注意到文档似乎使用 .render,而不是重定向。但这似乎要求我使用 .ejs,我不希望这样做。这是必须的吗?

++供参考++

 function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/login.html')
}
4

2 回答 2

3

所以我猜你让express.static()处理请求index.htmland login.html?在这种情况下,您可以创建一个index.html首先检查身份验证的路由,然后采取相应措施:

app.get('/index.html', ensureAuthenticated, function(req, res, next) {
  // if this block is reached, it means the user was authenticated;
  // pass the request along to the static middleware.
  next();
});

确保在添加到中间件堆栈之前express.static声明了上述路由,否则它将被绕过(快速中间件/路由按声明顺序调用,第一个匹配请求的将处理它)。

编辑:我一直忘记这是可能的,而且更清洁:

app.use('/index.html', ensureAuthenticated);

(而不是app.get上面的)

于 2013-04-15T17:01:30.087 回答
2

为什么你在每条路线上都使用重定向?你需要做的就是

app.get('/',ensureAuthenticated,function(req,res){

// your route logic goes here

});

ensureAutheticated 将检查您的代码是否经过身份验证。不需要每次通过登录路由都重定向它。

res.renderres.redirect()是用于不同目的的不同事物。

重定向重定向到 res.render() 呈现视图的路径。视图可以是consolidate.js支持的任何文件,如果您使用最新版本的 express,则必须使用该文件。

因此,从您的路由中删除所有这些重定向,无限循环应该停止。您只需要通过 ensureAuthenticated 以确保请求已通过身份验证。

于 2013-04-15T16:31:42.173 回答