Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express resources with authentication middleware?

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.

like image 987
Patrick Avatar asked Feb 09 '12 15:02

Patrick


People also ask

What is an authentication middleware?

Authentication middleware This middleware checks for a valid identity using the hasIdentity() method of AuthenticationService . If no identity is present, we redirect the redirect configuration value.

What is Express middleware?

js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response.


2 Answers

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

like image 68
Lan Avatar answered Sep 20 '22 23:09

Lan


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));
  }
});
like image 27
Patrick Avatar answered Sep 20 '22 23:09

Patrick