【问题标题】:Require Authentication for directory (except one page) with Passport.js / Node.js?需要使用 Passport.js / Node.js 对目录(一页除外)进行身份验证?
【发布时间】:2013-04-11 00:14:24
【问题描述】:

我刚开始使用 Passport.js,但我发现它到目前为止运行良好。我正在使用 Passport 和本地护照。

但是,我想要求对整个目录进行身份验证,不包括一页。所以在我的节点服务器中,我正在提供这个目录(使用 express):

app.use("/admin", express.static(__dirname + "/admin"));

然后我想让用户点击/admin/login.html,所以我想做这样的事情:

app.get('/gb-admin/login.html', function(req, res){ });

然后我想要求对其余部分进行身份验证,所以是这样的:

app.get('/gb-admin/*', ensureAuthenticated, function(req, res){});

这是我的 ensureAuthenticated 函数,如果有帮助,供参考:

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

我该怎么做呢?我通常一直在无限循环中发送东西并导致浏览器超时。有人可以帮忙吗?

【问题讨论】:

    标签: javascript jquery node.js authentication passport.js


    【解决方案1】:

    你得到超时的原因是你不能有一个空的路由处理程序;在某一时刻,您必须要么返回响应,要么将请求交给下一个路由处理程序/中间件。

    也就是说,试试这个:

    function ensureAuthenticated(req, res, next) {
      if (req.path === '/gb-admin/login.html' || req.isAuthenticated()) {
        return next();
      }
      res.redirect('/gb-admin/login.html')
    }
    
    app.get('/gb-admin/*', ensureAuthenticated, function(req, res, next) {
      next();
    });
    
    // the static middleware needs to be declared after the route above, otherwise
    // it will take precedence and ensureAuthenticated will never be called.
    app.use("/gb-admin", express.static(__dirname + "/admin"));
    

    我认为没有办法让它与登录页面的单独路由一起工作(除非您实际上实现读取 login.html 并在没有该路由处理程序的情况下将其发送回),因此在ensureAuthenticated 中间件。

    【讨论】:

    • 啊,太棒了!谢谢!也帮助我了解这里发生了什么。
    【解决方案2】:

    不知道是不是你的回调。试试:

    app.get('/gb-admin/*', function (req, res, next) {
      ensureAuthentication(req, res, next) {
        if (req.isAuthenticated()) { return next(); }
        res.redirect('/gb-admin/login.html')
      });
    });
    

    【讨论】:

    • 也感谢您的帮助!我没有测试你的解决方案,因为@robertklep 首先发布了他的答案,所以我坚持了下来。不过感谢您的帮助!
    猜你喜欢
    • 2023-04-05
    • 2017-08-20
    • 2023-04-03
    • 2012-10-31
    • 2018-05-03
    • 1970-01-01
    • 2022-06-26
    • 2020-01-02
    • 2018-03-08
    相关资源
    最近更新 更多