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.
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.
The basic authentication in the Node. js application can be done with the help express. js framework. Express.
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.
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.
Define your route for POST /users
before the blacklisted routes:
app.post('/users', function(req, res) {
...
});
app.all('*', asyncAuth, requestHandler);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With