简体   繁体   中英

Express basic authentication for serving static files

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.

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.

您是否尝试过以下方法:

app.use('/files/*', auth);

Okay, now my code looks like this:

app.use(function(req, res, next){
    if(req.url.indexOf('files') != -1) {
        return auth(req, res, next);
    } else {
        next();
    }
});

app.use('/files', auth);
app.use('/files', express.static(path.join(__dirname, 'files')));

But the problem exists still. That middleware seems to be used when I try to access "files" but If I try to access the file like /files/somefile.txt for some reason that middleware is skipped and I have access without authentication.

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.

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