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

我想检查我的networking应用程序的用户,当他们进入url的授权。 但是当我使用单独的中间件来检查授权时,对于已经存在的路由是没用的,比如:

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); 

authChecker无法检查进入这两个URL的用户的权限。 它只适用于未指定的url。

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

 app.get("/", authChecker, routes.index); 

但是我怎样才能以一种简单的方式实现它,而不是把AuthChecker放在每一条路线上呢?

非常感谢你..

只要

 app.use(authChecker); 

在之前

 app.use(app.router); 

它会被请求每一个请求。 然而,你会得到“太多的redirect”,因为它被称为ALL ROUTES ,包括/ auth 。 所以为了解决这个问题,我build议修改这个函数,如下所示:

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

这样你也不会redirectauth url。

有办法可以解决这个问题,但这是什么对我有用。

我喜欢为受保护和不受保护的路由创build一个中间件arrays,然后在必要时使用。

 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 }) 

通过编辑每种路由types的数组,可以轻松扩展每个中间件作用域的function。 它也使每条路线的function更加清晰,因为它告诉我们路线的types。

希望这可以帮助。

但是当我使用单独的中间件来检查授权时,对于已经存在的路由是没用的

Express将按照添加到堆栈的顺序运行中间件。 路由器是这些中间件function之一。 只要你把authChecker放到路由器的堆栈中,它就会被所有路由使用,事情就会起作用。

很有可能你在authChecker之前安装了路由器,因为你在authChecker进入堆栈之前已经定义了路由。 确保在app.getapp.post等的任何调用之前放置所有的app.use调用,以避免Express的app.post隐式注入路由器到中间件堆栈。