How best to restrict an httpNodeMiddleware function to certain endpoints

I am using some middleware functions to get authentication/authorization on my endpoints. (Doing it this way because I don't want to bother with that in my flows, and I want OAuth2 instead of basic auth.)

I got it working with the Auth0 service (let's you play for free!), and the express-openid-connect module.

I have this in my settings.js:

// at the top
const { auth, requiresAuth } = require('express-openid-connect');
// in  module.exports
	httpNodeMiddleware: [
			authRequired: false,
			issuerBaseURL: '',
			baseURL: 'https://localhost/',
			clientID: 'some id that I prefer not to share',
			secret: 'some secret that I prefer not to share',
			idpLogout: true,
			routes: {
				callback: '/mycallback'
		function (req, res, next) {
			var url = require("url");
			if (url.parse(req.url).pathname == '/test2') {
				requiresAuth()(req, res, next);
			} else {

The second function in the middleware is used to require auth only for my /test2 endpoint. But I find this approach not very elegant, when the express-openid-connect examples indicate that it can be done this way in "plain express.js":

app.get('/restricted', requiresAuth(), (req, res) =>
  res.send(`Hello ${req.oidc.user.sub}, this is the restricted section.`)

Does Node-RED also allow attaching a middleware to only some endpoints in a similar way, where you get to mention the path to the endpoint, and attach/inject a function?

Hi @mpolling

unfortunately the httpNodeMiddleware setting isn't that flexible. It gets applied to all routes - so you'd need to add some code at the start of the middleware to decide whether it should apply for the particular request and either return early or continue to handle the request.

Providing more flexible auth options to individual HTTP In nodes is something I've been thinking a bit about - but not something that's going to happen immediately.

Thanks for that. So, I guess my solution to check the path of the endpoint inside that middleware function, can be regarded best practice for now?
I.e., this little bit from the fragment above:

			if (url.parse(req.url).pathname == '/test2') {
				requiresAuth()(req, res, next);
			} else {
1 Like

Depending on what your endpoints are, you could instead try uibuilder which has its own middleware features.

At present its middleware is "global" to all uibuilder instances in Node-RED however, the next release should include per-instance middleware.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.