为服务静态文件提供基本身份验证

时间:2015-03-12 07:10:00

标签: node.js authentication express

我正在使用Express 4框架,我需要基本身份验证来提供静态文件。这就是我现在所拥有的:

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

如果我尝试访问/文件,但是如果我写了URL ./files/somefile.txt,则不需要身份验证,我可以访问该文件。我希望“files”目录下的所有文件只能由经过身份验证的用户访问。

4 个答案:

答案 0 :(得分:2)

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'}))

这是我的代码,它对我来说很好,你可以试试。

答案 1 :(得分:2)

您是否尝试过以下操作:

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

答案 2 :(得分:1)

好的,现在我的代码看起来像这样:

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')));

但问题仍然存在。当我尝试访问“文件”时,似乎会使用该中间件但是如果我尝试访问像/files/somefile.txt这样的文件,出于某种原因,中间件被跳过,我无需身份验证即可访问。

答案 3 :(得分:1)

这是一个老线程,但我遇到了同样的问题。我正在使用http-auth包来限制对公共目录中文件夹的访问。

中间件在请求受保护目录时正常工作(get / protectedFolder显示身份验证提示),但是当它们被直接请求时它会跳过文件(get /protectedFolder/file.txt显示文件内容。 TXT)

我通过切换中间件的顺序来解决它,我最初有

  app.use('/protected', express.static(path.join(__dirname, '../../../protected')));
  app.use('/protected', auth.connect(basic), (req, res, next) => {
      next();
  });

但正确的顺序应该是:

  app.use('/protected', auth.connect(basic), (req, res, next) => {
      next();
  });
  app.use('/protected', express.static(path.join(__dirname, '../../../protected')));

我希望这有助于某人。

相关问题