【问题标题】:Infinite loop in authentication redirection in nodejs appnodejs应用程序中身份验证重定向的无限循环
【发布时间】:2017-02-03 19:17:12
【问题描述】:

在使用用户身份验证时,我在重定向期间面临无限循环。

以下是 app.js 中的代码片段:

const hauthen = require('./handlers/hauthen');

const routes = require('./routes/index');
const authen = require('./routes/authen');
const users = require('./routes/users');

app.use(hauthen);

// routes
app.use('/', routes);
app.use('/authen', authen);
app.use('/users', users);

而这段代码来自认证页面hauthen.js:

router.all("/authen", (req, res, next) => {
    if (req.authen) {
        res.redirect("/");
    } else {
        next();
    }
});

router.all("*", function(req, res, next) {
    if (req.authen !== undefined) {
        next();
    } else {
        res.redirect('/authen');
    }
});

基本思想是如果用户尚未通过身份验证,则重定向到登录页面。但我在控制台中得到了根 url“/”的这个。

GET / 302 16.464 ms - 58
GET /authen 302 2.930 ms - 58
GET /authen 302 1.587 ms - 58
GET /authen 302 0.854 ms - 58
GET /authen 302 1.467 ms - 58
GET /authen 302 1.878 ms - 58
GET /authen 302 0.681 ms - 58

那么,是什么导致了无限重定向问题以及如何解决呢? 我做错了吗?

【问题讨论】:

    标签: javascript node.js authentication redirect


    【解决方案1】:

    问题在于定义的两条路线。

    router.all("/authen", (req, res, next)
    

    router.all("*", function(req, res, next)
    

    重定向正常。但是一旦重定向,next() 函数会将其带到下一个路由,即“router.all('*', .....”。这就是创建循环的地方。我将路由更改如下解决了这个问题。

    router.all("*", (req, res, next) => {
        if (req.authen !== undefined) {
            if(req.url === "/authen" || req.url === "/authen/") {
                res.redirect("/");
            } else {
                next();
            }
        } else {
            if(req.url === "/authen" || req.url === "/authen/") {
                next();
            } else {
                res.redirect('/authen');    
            }
        }
    });
    

    【讨论】:

      【解决方案2】:

      为避免无限循环并保护项目中的路由,您可以在文件 hauthen.js 中创建特定的路由中间件函数,以检查用户是否已通过身份验证:

      // Check if user is authenticated
      function isAuthenticated(req, res, next) {
          if (req.user && req.user.authenticated) {
              return next();
          }
      
          // If user isn't authenticated, then redirect somewhere
          res.redirect('/login');
      }
      

      您可以在要保护的路由中使用中间件:

      router.get('/protected', isAuthenticated, function(req, res) {
          res.send('Protected route!');
      });
      

      【讨论】:

      • 我知道这种方法。但是这样我需要将 isAuthenticated 函数传递给每条路由。相反,我想一次为所有路线执行此操作。
      • 尽你所能 router.all('*', isAuthenticated);并记住从 isAuthenticated 中间件中排除路由 /login
      【解决方案3】:

      / 重定向到authenauthen 重定向到/ 或继续到/(下一个) 这是一个循环。

      【讨论】:

      • next() 是否在此处继续“/”?我怎样才能让它继续到用户路线的下一条路线。我的意图是继续使用 next() 的用户。
      • 如果定义了 authen,那么它将从 / 到 .authen 来回移动。
      猜你喜欢
      • 1970-01-01
      • 2014-05-28
      • 2013-04-07
      • 1970-01-01
      • 2017-11-07
      • 2015-12-13
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多