Search code examples
node.jsexpressstormpath

NodeJS and Express: Add auth middleware to static path


I have a node app running express as the web app framework and I use Stormpath for authentication.

Storm path gives the ability to protect a route with several middlewares, for example:

router.get('/user_data_api', stormpath.apiAuthenticationRequired, function(req, res) {
        res.send('hello you are authenticated!");
     });
});

What I want to do is to add authenticationRequired as a middleware to the static definition of express:

app.use(express.static(__dirname + '/public'));

This could be achieved by adding a route to the static assets, so if I have a file ./public/index.html I can set the route like this:

app.use('/secured-assets', 
               stormpath.auth_fn, express.static(__dirname + '/public'));

But then the file will be in

www.mydomain.com/secured-assets/index.html

And I want it in

www.mydomain.com/index.html

Help?


Solution

  • Do just:

    app.use(stormpath.auth_fn, express.static(__dirname + '/public'));
    

    It'll add stormpath.auth_fn and express.static(__dirname + '/public') middlewares to the / path and, hence, will protect every route.