node.js - 导致无限循环的快速身份验证重定向

标签 node.js authentication express infinite-loop passport.js

我正在尝试使用 express 在 node.js 服务器上设置 Passport 本地身份验证。看起来它应该非常简单。但是我卡住了。

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

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,而不是重定向。但是这个 SEEMS 要求我使用 .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 中间件/路由按顺序调用声明,第一个匹配请求的将处理它)。

编辑:我一直忘记这是可能的,而且也更干净:

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

(而不是上面的app.get)

关于node.js - 导致无限循环的快速身份验证重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16019830/

相关文章:

node.js - AWS Elasticsearch:putSettings 'is not allowed'的关闭索引?

javascript - 如何在构造函数中执行异步函数?

asp.net - Windows 身份验证仅限于特定域

vue.js - *Nuxt JS Auth* 为什么在模板部分使用 loginWith 成功登录后 auth.loggedIn 为真,但在中间件文件中为假?

javascript - 为什么我们需要重启 Express 服务器才能在浏览器上看到变化?

node.js - Express JS 验证器函数错误

javascript - 如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接

node.js - 如何将 Bazel 与 Node.js 结合使用

javascript - 如何使用 Passport 保护路由端点?

node.js - NodeJS/express : Cache and 304 status code