About many things

HTTP Authentication with Node.js

Everyone familiar with Apache HTTP Server knows the most popular way of setting up HTTP Basic / Digest access authentication.

Yes! I want to write about .htpasswd and .htdigest files and how can you use them in your Node.js application. In this article I will write about http-auth module that I created to support .htpasswd and .htdigest files in Node.js applications.

Installation

The best way of installing it is via npm:

$ npm install http-auth

Usage

Depending what type of authentication you want to use you should call corresponding method auth.basic or auth.digest. You can view available configurations in configurations section.

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd"
});

// Creating new HTTP server.
http.createServer(basic, function(req, res) {
    res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);

You might notice that application is calling http.createServer with mutated argument list, which is strange.

Correct! Application is changing native node.js method to provide some flexibility in usage. You might say that it is not future proof and one should never change what he / she does not own.

You are right, I just thought that there is very little possibility that the most used method in Node.js will be changed.

Integrations

Module has integrations with some popular Node.js modules and for sure the most important one is express.js integration.

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd"
});

// Application setup.
var app = express();
app.use(auth.connect(basic));

// Setup route.
app.get('/', function(req, res){
  res.send("Hello from express - " + req.user + "!");
});

Command line tools

As a bonus you can install htpasswd or htdigest command line tools using npm. Those should provide functionality similar to Apache’s tools.

$ npm install -g htpasswd

or

$ npm install -g htdigest
#node.js