在进入每个路由之前如何使用中间件来检查授权? [英] How to use the middleware to check the authorization before entering each route in express?

查看:141
本文介绍了在进入每个路由之前如何使用中间件来检查授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们的网页应用进入网址时,我想检查用户的授权。但是当我使用一个单独的中间件来检查授权时,对已经存在的路由来说是无用的,例如:

  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 未启用,以检查输入的用户的权限两个网址
它只适用于未指定的网址。



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

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

但是如何以简单的方式实现它,而不是将authChecker放在每个路由中? p>

非常感谢..

解决方案

只要

  app.use(authChecker); 

 code> app.use(app.router); 

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

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

这样你就不会重定向到auth url


I want to check the authorization of the users of my web app when they entered the url. But when I used an individually middleware to check the authorization, it's useless for the already existing routes, such as:

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

The authChecker is unabled to check the authority of the users who entered the two urls. It only works for the unspecified urls.

And I saw a method that I can put the authChecker between the route and the route handler, such as:

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

But How can I achieve it in a simple way rather than putting the authChecker in every route?

Thank you very much..

解决方案

As long as

app.use(authChecker);

is before

app.use(app.router);

it will get called for every request. However, you will get the "too many redirects" because it is being called for ALL ROUTES, including /auth. So in order to get around this, I would suggest modifying the function to something like:

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

This way you won't redirect for the auth url as well.

这篇关于在进入每个路由之前如何使用中间件来检查授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆