Ben Diamant
Ben Diamant

Reputation: 6206

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?

Upvotes: 2

Views: 1321

Answers (2)

Mark
Mark

Reputation: 137

This worked for me with Express ^4.13.4 and Stormpath ^3.1.2

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

Upvotes: 0

alexpods
alexpods

Reputation: 48525

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.

Upvotes: 4

Related Questions