It looks like implementing basic HTTP authentication with Express v3 was trivial:
app.use(express.basicAuth(\'username\', \'password\'));
V
express.basicAuth
is gonebasic-auth-connect
is deprecatedbasic-auth
doesn't have any logichttp-auth
is an overkillexpress-basic-auth
is what you wantSince you're using Express then you can use the express-basic-auth
middleware.
See the docs:
Example:
const app = require('express')();
const basicAuth = require('express-basic-auth');
app.use(basicAuth({
users: { admin: 'supersecret123' },
challenge: true // <--- needed to actually show the login dialog!
}));
A lot of the middleware was pulled out of the Express core in v4, and put into separate modules. The basic auth module is here: https://github.com/expressjs/basic-auth-connect
Your example would just need to change to this:
var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));
I used the code for the original basicAuth to find the answer:
app.use(function(req, res, next) {
var user = auth(req);
if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
res.end('Unauthorized');
} else {
next();
}
});