Is it possible to apply basic authentication / middleware on routes using the whitelist in Express?

I am implementing a RESTful API with Express in Node and I am new to both. I would like to use basic authentication for access control.

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

Blacklisting is easy, I can simply transfer my #VERB calls with a second argument:

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

I can do it even further, and blacklist with

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

But I want to apply my basicAuth to every route except for POST /users . Is there an elegant way to do this? Can I use the blacklist approach and then selectively remove it from the routes I need? I could not understand how.

+6
source share
2 answers

Define a route for POST /users before blacklists:

 app.post('/users', function(req, res) { ... }); app.all('*', asyncAuth, requestHandler); 
+8
source

You can save the list of regular expressions that are in the white list and map the URL to each URL in the list, if it matches any of them, and then requires authorization

 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 these lines

+2
source

All Articles