Basic Auth With Express 4

written in javascript

I’ve only more recently started using Express 4 instead 3.x for building APIs with Node.js. The framework saw quite a bit of refactoring, and has lead to a noticeable amount of confusion on GitHub and StackOverflow.

One of these issues is using basic auth middleware with Express 4. Where is it? It’s gone! Poof. Vanished. The alternatives? basic-auth-connect had been previously recommended, but is now deprecated. Thankfully, it’s a simple concept made even easier to implement with the use of basic-auth.

So, let’s get started by running this command in your app root dir:

1
npm install --save basic-auth

Now to write the middleware. I’m going to assume you have a file containing express utility and helper functions. For this example, let’s assume it’s named utils.js, and we’ll add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Your utility library for express
 */

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

/**
 * Simple basic auth middleware for use with Express 4.x.
 *
 * @example
 * app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
 *
 * @param   {string}   username Expected username
 * @param   {string}   password Expected password
 * @returns {function} Express 4 middleware requiring the given credentials
 */
exports.basicAuth = function(username, password) {
  return function(req, res, next) {
    var user = basicAuth(req);

    if (!user || user.name !== username || user.pass !== password) {
      res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
      return res.send(401);
    }

    next();
  };
};

Simple, right? To use it, just require the module, and load the middleware for your desired path.

1
2
3
4
var utils = require('./utils');

// Before any of the relevant routes...
app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));

Comments