Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

node.js - How to use the middleware to check the authorization before entering each route in express?

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?

question from:https://stackoverflow.com/questions/18700729/how-to-use-the-middleware-to-check-the-authorization-before-entering-each-route

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...