Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect static folder in express with passport

I have a project based on express with a required authentication based on passport.

The backoffice is an angularjs app served as static files.

My authentication code is completly based on https://github.com/jaredhanson/passport-local/blob/master/examples/express3-no-connect-flash/app.js

To do not serve the angular app if you are not authenticated. I have try by adding ensureAuthenticated on the /admin route but it make the route not working (404). Once I remove ensureAuthenticated the /admin is served.

app.use(express.static(path.join(__dirname, 'public'))); app.use('/admin', ensureAuthenticated, express.static(path.join(__dirname, 'admin'))); //serve routes app.use(app.router); 

The public folder contains the login page.

How could I achieve this ?

like image 508
toutpt Avatar asked Jan 24 '14 15:01

toutpt


People also ask

What is static folder in Express?

Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.


2 Answers

Ran into same issue, this is what I ended up doing!

app.use doesn't let you chain middlewares in that way. The various app.VERB functions do, but app.use doesn't. That's for one middleware at a time.

If you split the 2 middlewares out into separate calls, you should get the results you want:

app.use('/admin', ensureAuthenticated); app.use('/admin', express.static(path.join(__dirname, 'admin'))); 

Cannot use basic authentication while serving static files using express

like image 106
Bobz Avatar answered Sep 21 '22 18:09

Bobz


You can check the route using middleware and redirect them if they aren't logged in and are hitting admin pages, something like (untested):

app.use(function(req, res, next) {     if (req.user == null && req.path.indexOf('/admin') === 0)     {         res.redirect('/login');     }     next();  }); 
like image 45
MikeSmithDev Avatar answered Sep 22 '22 18:09

MikeSmithDev