快速认证重定向导致无限循环



我正在尝试使用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,而不是redirect。但这似乎要求我使用。ejs,我宁愿不这样做。这是必须的吗?

+ + + +供参考

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

所以我猜你让express.static()处理index.htmllogin.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到中间件堆栈之前声明上述路由,否则它将被绕过(Express中间件/路由按声明顺序调用,第一个匹配请求的将得到处理)。

EDIT:我总是忘记这是可能的,而且更干净:

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

(代替上面的app.get)

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

app.get('/',ensureAuthenticated,function(req,res){
// your route logic goes here
});

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

res。Render和res.redirect()是不同的东西,用于不同的目的。

Redirect重定向到as res.render()渲染视图。视图可以是任何由consolidated .js支持的文件,如果你正在使用最新版本的express,你必须使用这个文件。

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

最新更新