Modulus

Node.js and Express - Basic Authentication

Node.js and Express - Basic Authentication

Basic authentication can be a quick and efficient way to protect your content. Combined with SSL it’s also very secure. This article describes how to add basic authentication to a Node.js Express application.

Express App

The first thing we need is an Express application. Creating an Express app is extremely simple, and the makers of Express do a pretty good job documenting the process.

package.json

{
  "name" : "BasicAuthExample",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.x"
  }
}

app.js

var express = require('express');
var app = express();

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

The application has one route defined, /home. Right now there is no authentication. Anyone can access /home and see the content. If you host the application on Modulus the PORT environment variable will be defined, otherwise I’m simply using 8080.

Global Authentication

The first technique we’ll see is adding authentication globally to every route. Fortunately with Express, we can do this with a single line.

Synchronous

This technique is the simplest, but least flexible. The authentication will occur synchronously with hard-coded values.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(‘testUser’, 'testPass'));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

In this example, to access any route in our application the user must enter the username, ‘testUser’, and the password, ‘testPass’.

Synchronous Function

The second technique is also synchronous, but provides a little more flexibility. This time we’re going to define a function that simply has to return true or false.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass) {
 return user === 'testUser' && pass === 'testPass';
}));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

As you can see, we now pass a function as the authentication mechanism instead of the username and password. The function gets as arguments the username and password specified by the user. Technically you don’t even need to use these as part of the authentication, since all you have to do is return true or false.

Asynchronous

The last technique is the most flexible. With an async callback you could lookup the username and password in a database.

var express = require('express');
var app = express();

// Authenticator
app.use(express.basicAuth(function(user, pass, callback) {
 var result = (user === 'testUser' && pass === 'testPass');
 callback(null /* error */, result);
}));

app.get('/home', function(req, res) {
 res.send('Hello World');
});

app.listen(process.env.PORT || 8080);

This example also takes a function, but instead of only passing the username and password, it also passes a callback function that should be invoked with the result. The callback utilizes the error-first pattern, so the first parameter should be null if no errors occurred. The second parameter to the callback is the result (true or false) of the authentication.

Single-Route Authentication

The above three techniques can also be used to secure individual routes. Just like before we define our authentication handler, except this time we need to save it to a variable.

// Synchronous
var auth = express.basicAuth('testUser', 'testPass');

// Synchronous Function
var auth = express.basicAuth(function(user, pass) {
 return user === 'testUser' && pass === 'testPass';
});

// Asynchronous
var auth = express.basicAuth(function(user, pass, callback) {
 var result = (user === 'testUser' && pass === 'testPass');
 callback(null /* error */, result);
});

All that we have to do now is pass the authenticator to the routes we’d like protected.

app.get('/home', auth, function(req, res) {
 res.send('Hello World');
});

app.get('/noAuth', function(req, res) {
 res.send('Hello World - No Authentication');
});

As you can see, the /home route still requires authentication since we’ve passed the authenticator as the second parameter. The /noAuth route is publically available since an authenticator was not supplied.

And there you have it. We’ve seen all the ways to add basic authentication to your Node.js Express application. If you’ve got any questions or comments leave them in the comments below.

What is Modulus?

Modulus is a home for web applications. Node.js hosting, integrated MongoDB, and performance metrics all in one place. It’s free to get started.

Share This Article

comments powered by Disqus