如何在快递中输入每条路线之前使用中间件检查授权?

Noa*_*ues 33 middleware node.js express

我想在输入网址时检查我的网络应用用户的授权.但是,当我使用单独的中间件来检查授权时,它对已有的路由没用,例如:

function authChecker(req, res, next) {
    if (req.session.auth) {
        next();
    } else {
       res.redirect("/auth");
    }
}

app.use(authChecker);
app.get("/", routes.index);
app.get("/foo/bar", routes.foobar);
Run Code Online (Sandbox Code Playgroud)

该authChecker是unabled检查谁进入两个URL的用户的权限.它仅适用于未指定的URL.

我看到了一种方法,我可以将authChecker放在路由和路由处理程序之间,例如:

app.get("/", authChecker, routes.index);
Run Code Online (Sandbox Code Playgroud)

但是,我怎样才能以简单的方式实现它,而不是将authChecker放在每个路径中?

guy*_*g28 34

只要

app.use(authChecker);
Run Code Online (Sandbox Code Playgroud)

在此之前

app.use(app.router);
Run Code Online (Sandbox Code Playgroud)

每次请求都会调用它.但是,您将获得"太多重定向",因为它被调用所有路由,包括/ auth.所以为了解决这个问题,我建议将函数修改为:

function authChecker(req, res, next) {
    if (req.session.auth || req.path==='/auth') {
        next();
    } else {
       res.redirect("/auth");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样您也不会重定向到auth url.


sin*_*axi 24

有可能解决这个问题的方法,但这对我有用.

我喜欢为受保护和不受保护的路由创建一系列中间件,然后在必要时使用.

var protected   = [authChecker, fetchUserObject, ...]
var unprotected = [...]

app.get("/", unprotected, function(req, res){
  // display landing page
})

app.get("/dashboard", protected, function(req, res){
  // display private page (if they get this far)
})

app.get("/auth", unprotected, function(req, res){
  // display login form
})

app.put("/auth", unprotected, function(req, res){
  // if authentication successful redirect to dashboard
  // otherwise display login form again with validation errors
})
Run Code Online (Sandbox Code Playgroud)

这样,通过编辑每种类型路由的数组,可以轻松扩展每个中间件范围的功能.它还使每条路线的功能更加清晰,因为它告诉我们路线的类型.

希望这可以帮助.

  • 当你有很多路由时,如何处理这种情况,将受保护/不受保护的数组放在每个路由中? (7认同)