用于提供静态文件的快速基本身份验证

otr*_*rec 5 authentication node.js express

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

app.use('/files', auth);
app.use('/files', express.static(path.join(__dirname, 'files')));
Run Code Online (Sandbox Code Playgroud)

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

Zin*_*ebM 5

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

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

我通过切换中间件的顺序解决了这个问题,我最初有

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

但正确的顺序应该是:

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

我希望这可以帮助别人。


Bla*_*mba 3

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'}))
Run Code Online (Sandbox Code Playgroud)

这是我的代码,对我来说效果很好,你可以尝试一下。