【问题标题】:Express basic authentication for serving static files用于提供静态文件的 Express 基本身份验证
【发布时间】:2018-02-14 17:28:06
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js authentication express


    【解决方案1】:

    您是否尝试过以下方法:

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

    【讨论】:

    • 我遇到过的最好/最简单的答案之一。谢谢!
    【解决方案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'}))
    

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

    【讨论】:

    • 还是一样,如果我尝试直接访问 /ftp/somefile.txt,则会跳过 auth-middleware。我也尝试过表达 3,但同样的事情发生了。如果 somefile.txt 不存在,这可以正常工作并询问用户/密码。但是如果文件存在,我的浏览器会在没有身份验证的情况下打开它。
    【解决方案3】:

    这是一个旧线程,但我刚刚遇到了同样的问题。我正在使用 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')));
    

    我希望这对某人有所帮助。

    【讨论】:

      最近更新 更多