nodejs app中的身份验证重定向中的无限循环

时间:2016-09-26 12:33:00

标签: javascript node.js authentication redirect

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

以下是来自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

那么,是什么导致了infinte重定向问题以及如何修复它? 我是以错误的方式做的吗?

3 个答案:

答案 0 :(得分:1)

为避免无限循环并保护项目中的路线,您可以在文件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!');
});

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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');    
        }
    }
});
相关问题