Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Noah Blues Avatar asked Sep 09 '13 14:09

Noah Blues


People also ask

Which middleware is used to handle the routing logic in Express?

Express. js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response.

Where can I use middleware in Express?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.


1 Answers

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.

like image 164
guydog28 Avatar answered Sep 18 '22 22:09

guydog28