简体   繁体   中英

Restricting access to static files in ExpressJS

I have a server that routes pretty much everything through middleware to check to see if you're logged in, but that only works for routes. I would also like it to work with static files in the public directory. How would I go about doing that?

update : it's better to not worry about protecting what's in the /public folder because express offers a res.download(...) feature. Example on the Express.JS GitHub page

To clarify static files are also server by express using the express.static middleware. In theory you can include middleware before it to handle the security. Besides the idea of the static middleware is that you only make the folder public statically available since its public .

You can find static defined here. You can either rewrite it to allow you to inject middleware into it.

Or you can just write a naive static file router yourself.

Have you tried injecting your own security log in middleware before your static middleware.

app.use(security);
app.use(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