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();
}
});
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:
Simple Basic Auth with vanilla JavaScript (ES6)
Why?
req.headers.authorization
contains the value "Basic <base64 string>
", but it can also be empty and we don't want it to fail, hence the weird combo of|| ''
atob()
andbtoa()
, hence theBuffer
ES6 -> ES5
const
is justvar
.. sort of(x, y) => {...}
is justfunction(x, y) {...}
const [login, password] = ...split()
is just twovar
assignments in onesource of inspiration (uses packages)
The above is a super simple example that was intended to be super short and quickly deployable to your playground server. But as was pointed out in the comments, passwords can also contain colon characters
:
. To correctly extract it from the b64auth, you can use this.On the other side, if you only ever use one or very few logins, this is the bare minimum you need:
(you don't need to parse the credentials)
BTW, do you need to have both secure and "public" paths? Consider using
express.router
instead.I changed in express 4.0 the basic authentication with http-auth, the code is:
We can implement the basic authorization without needing any module
Source:- http://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs
There seems to be multiple modules to do that, some are deprecated.
This one looks active:
https://github.com/jshttp/basic-auth
Here's a use example:
Make sure you put the
auth
middleware in the correct place, any middleware before that will not be authenticated.TL;DR:
☒
express.basicAuth
is gone☒
basic-auth-connect
is deprecated☒
basic-auth
doesn't have any logic☒
http-auth
is an overkill☑
express-basic-auth
is what you wantMore info:
Since you're using Express then you can use the
express-basic-auth
middleware.See the docs:
Example: