It looks like implementing basic HTTP authentication with Express v3 was trivial:
app.use(express.basicAuth('username', 'password'));
Version 4 (I'm using 4.2) removed the basicAuth
middleware, though, so I'm a little stuck. I have the following code, but it doesn't cause the browser to prompt the user for credentials, which is what I'd like (and what I imagine the old method did):
app.use(function(req, res, next) {
var user = auth(req);
if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
res.end('Invalid credentials');
} else {
next();
}
});
I used the code for the original
basicAuth
to find the answer:Express has removed this functionality and now recommends you use the basic-auth library.
Here's an example of how to use:
To send a request to this route you need to include an Authorization header formatted for basic auth.
Sending a curl request first you must take the base64 encoding of
name:pass
or in this casealaddin:opensesame
which is equal toYWxhZGRpbjpvcGVuc2VzYW1l
Your curl request will then look like: