Express resources with authentication middleware?

12,158

Solution 1

I know this is a little too late, and the original post was answered, however, I was looking for the same answer and found a solution I thought others might want to know.

Just make sure ensureAuthenticated is called from passport.

    app.resource('users', passport.ensureAuthenticated, require('./resources/users'));

It is found here: https://gist.github.com/1941301

Solution 2

Workaround. Ensure authentication on all requests and ignore requests going to /auth and /auth/callback.

app.all('*', function(req, res, next) {
  if (/^\/auth/g.test(req.url)) {
    return next();
  } else if (req.isAuthenticated()) {
    return next();
  } else {
    return next(new Error(401));
  }
});

Solution 3

You will need to do some magic in order to have each resource use the authentication middleware. The following gist explains how to accomplish this by using a menu structure.

https://gist.github.com/3610934

Essentially, you need the following logic:

app.all('/' + item.name + '*', ensureAuthenticated, function (req, res, next) {
  next();
});

You could then in your menu structure specify what resources are protected, and if they require any kind of specific permissions, even down to the HTTP method level.

Hopefully this helps someone!

Share:
12,158
Patrick
Author by

Patrick

Location independent software nerd. I love breaking down complex situations into simple and minimalistic solutions. Available for new contracts anywhere in the world. #nodejs #javascript #devops #serverless

Updated on June 04, 2022

Comments

  • Patrick
    Patrick almost 2 years

    Passport.js offers great authentication for node.js and Express including a middleware solution:

    ensureAuthenticated = function(req, res, next) {
      if (req.isAuthenticated()) {
        return next();
      }
      return res.redirect("/login");
    };
    

    How can I use this middleware in the express-resource module? Unfortunately,

    app.resource('users', ensureAuthenticated, require('./resources/users'));
    

    doesn't work.