expressjs / serve-static

Serve static files
MIT License
1.38k stars 227 forks source link

Password protect a folder with HTTP Basic Authentication #112

Closed 1Map closed 6 years ago

1Map commented 6 years ago

How would I go about to password protect a folder where user needs to enter password before downloading any file?

1Map commented 6 years ago

No Problem, I found a solution, for those who are looking for one (It is basically to do with serve-index):

var express = require('express')
var serveIndex = require('serve-index')
var auth = require('http-auth')

// Configure basic auth
var basic = auth.basic({
  realm: 'SUPER SECRET STUFF'
}, function (username, password, callback) {
  callback(username == 'admin' && password == 'f00lpr00f')
});

var app = express()

// Create middleware that can be used to protect routes with basic auth
var authMiddleware = auth.connect(basic)

// Serve URLs like /ftp/thing as public/ftp/thing
// The express.static serves the file contents
// The serveIndex is this module serving the directory
app.use('/', authMiddleware, express.static('public/installs'), serveIndex('public/installs', {
  'icons': true
}))

// Listen
app.listen(1338)