Reputation: 51
I'm using Express 4 framework and I need basic authentication for serving static files. This is what I have now:
app.use('/files', auth);
app.use('/files', express.static(path.join(__dirname, 'files')));
This works great if I try to access /files but if I wrote URL ../files/somefile.txt authentication is not needed and I'm able to access that file. I would want all the files under the "files"-directory to be accessible only by authenticated user.
Upvotes: 5
Views: 5348
Reputation: 21
app.use('/files', auth , express.static(path.join(__dirname, 'files')));
Upvotes: 2
Reputation: 119
It's an old thread but I just came across the same issue. I'm using http-auth package to restrict the access to a folder in my public directory.
The middleware was working fine when requesting the protected directory (get /protectedFolder shows the prompt for the authentication), but it skips the files when they're requested directly (get /protectedFolder/file.txt displays the content of file.txt)
I solved it by switching the order of middlewares, I initially had
app.use('/protected', express.static(path.join(__dirname, '../../../protected')));
app.use('/protected', auth.connect(basic), (req, res, next) => {
next();
});
But the correct order should be:
app.use('/protected', auth.connect(basic), (req, res, next) => {
next();
});
app.use('/protected', express.static(path.join(__dirname, '../../../protected')));
I hope this helps someone.
Upvotes: 5
Reputation: 10254
var basicAuth = require('basic-auth');
var auth = function(req, res, next){
var user = basicAuth(req);
if(user && user.name == "admin" && user.pass == "admin")
return next();
else{
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
}
}
app.use(function(req, res, next){
if(req.url.indexOf('ftp') != -1){
console.log(req.url);
return auth(req, res, next);
}
else
next();
});
app.use(express.static(path.join(__dirname, 'public')));
app.use('/ftp', serveIndex('public/ftp', {'icons': true, 'hidden': true, 'view': 'details'}))
Here is my code, it works fine for me, you can try it.
Upvotes: 3