简体   繁体   中英

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?

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.

这适用于Express ^ 4.13.4和Stormpath ^ 3.1.2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM