Skip to main content

Express.js 4.0 BasicAuth

Express 4.0 was recently released, with one of the major changes being that connect middleware is no longer available on the express module. This means no basic http authentication unless you do it yourself. Other people may find this easy, but I had to look it up, so to help people like me here are some quick instructions on getting it going again.

First, visionmedia has release a package called "basic-auth", but that simply parses req.headers.authorization into a user object like { name: 'foo', pass: 'bar' }. It's useful, so install it.

npm install basic-auth

Next we need to require basic-auth and create some middleware to handle the actual authentication.

var basicAuth = require('basic-auth');

var auth = function (req, res, next) {
  function unauthorized(res) {
    res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
    return res.send(401);
  };

  var user = basicAuth(req);

  if (!user || !user.name || !user.pass) {
    return unauthorized(res);
  };

  if (user.name === 'foo' && user.pass === 'bar') {
    return next();
  } else {
    return unauthorized(res);
  };
};

Basic-auth parses the req.authorization.header into a user object. If the user object does not exist, then return unauthorized. If the user object exists, then check it against the authorization, if correct return next, else return unauthorized.

All you need to do now is to include the auth variable in the routes you'd like authenticated, like this:

app.get('/', auth, function (req, res) {
  res.send(200, 'Authenticated');
};

And there you have your basic authentication back. The original code for the Express 3 basic auth can be found here.