Cannot use basic authentication while serving static files using express

前端 未结 4 1691
谎友^
谎友^ 2021-02-12 19:29

Using the Express framework for node.js, I\'m trying to serve up static files contained in a directory while also putting basic authentication on it. When I do so, I am prompted

4条回答
  •  有刺的猬
    2021-02-12 19:57

    I thought I'd post the express 4 answer here, since there's no other post title as fitting as this one for this specific use-case, and it may be relevant for more people.

    If you're using express 4, chances are you're using serve-index, serve-static, and http-auth (unless there's an easier way that I'm missing out on):

    serveIndex = require('serve-index'),
    serveStatic = require('serve-static'),
    auth = require('http-auth');     
    
    // Basic authentication
    var basic = auth.basic({
            realm: "My Secret Place.",
        }, function (username, password, callback) { // Custom authentication method.
            callback(username === "me" && password === "mepassword");
        }
    );
    
    var authMiddleware = auth.connect(basic);
    
    // Serve /secretplace as a directory listing
    app.use('/secretplace', authMiddleware, serveIndex(__dirname + '/public/secretplace'));
    
    // Serve content under /secretplace as files
    app.use('/secretplace', serveStatic(__dirname + '/public/secretplace', { 'index': false }));
    

    Note, as far as my testing, I didn't need to pass 'authMiddleware' when setting serveStatic.

提交回复
热议问题