Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply basic authentication / middleware in on routes with a whitelist in Express?

I'm implementing a RESTful API with Express in Node, and I'm new to both. I'd like to use basic authentication to control access.

I would like to apply it using something like a whitelist but I'm not sure how to do that.

Blacklisting is easy, I can just pepper my #VERB calls with the second argument:

app.get('/', asyncAuth, requestHandler);

I can take that even further and blacklist everything with:

app.all('*', asyncAuth, requestHandler);

But I want to apply my basicAuth to every single route, except for POST /users. Is there an elegant way to do that? Can I use the 'blacklist' approach then selectively remove it from the routes I'd like? I couldn't figure out how.

like image 305
Terraflubb Avatar asked Mar 15 '13 04:03

Terraflubb


People also ask

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

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router() . Load router-level middleware by using the router.use() and router.METHOD() functions.

Does Express support HTTP basic authentication?

The basic authentication in the Node. js application can be done with the help express. js framework. Express.

How do I exclude a route from middleware?

To exclude a route from running an Express middleware, we can create our own function that accepts a route path and middleware function and returns a middleware function that checks the route path before running the middleware function.

How is middleware added to an Express application?

use() to add a middleware function to our Express application. Express will first execute function1 and then function2 . Middleware functions in Express are of the following types: Application-level middleware which runs for all routes in an app object.


2 Answers

Define your route for POST /users before the blacklisted routes:

app.post('/users', function(req, res) {
  ...
});

app.all('*', asyncAuth, requestHandler);
like image 68
robertklep Avatar answered Nov 15 '22 07:11

robertklep


You could maintain a list of regexps that are whitelisted, and match the url against each url in the list, if it matches any then proceed, else require auth

app.all('*', asyncAuth);

function asyncAuth(req, res, next) {
    var done = false;
    whitelist.forEach(function(regexp) {
        if (req.url.match(regexp)) {
            done = true;
            next();
        }
    });
    if (!done) requireAuth(next);
}

Something along those lines

like image 33
Benoir Avatar answered Nov 15 '22 06:11

Benoir