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

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

问题描述

我想在我的网络应用程序的用户输入 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);

authChecker 无法检查输入这两个网址的用户的权限.它仅适用于未指定的网址.

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

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

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

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

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

推荐答案

只要

app.use(authChecker);

app.use(app.router);

每次请求都会调用它.但是,您会得到重定向过多",因为它被ALL ROUTES 调用,包括/auth.因此,为了解决这个问题,我建议将该函数修改为:

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

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

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

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

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