Friday, January 31, 2014

Creating the simplest HTTP server with basic authentication using node.js

        In this article I will show you how to create the simplest possible HTTP server with basic authentication in node.js. I have to warn you though, I needed a quick and dirty solution for testing purposes, so this is definitely not for production use. You should at least keep hashes of user passwords, not plaintext passwords themselves, and use digest authentication as a more secure method.
        First, install the htpasswd module globally:
npm install -g htpasswd
        Create a directory for your project and install http-auth module locally:
npm install http-auth
        Create a file auth-server.js with your editor of choice. Put the following lines into it:
var http = require("http");
var auth = require("http-auth");

var basic = auth.basic({
    file: __dirname + '/htpasswd'

http.createServer(basic, function(req, res) {
    console.log('Received request: ' + req.url);
    res.end('User successfully authenticated: ' + req.user);
        Now create a file htpasswd in the same directory and populate it with a user name and a password separated by a colon:
        Now run the node server:
node auth-server.js
        Go to the http://localhost:8080 URL in your browser. It will greet you with a standard basic-auth panel to enter your username and password. After successful authentication, you will see the message from server.
        For more info on how to use the http-auth package for basic and digest authentication, see its page on github: For more info on htpasswd module, including using different types of hashes instead of plain text passwords, see

1 comment:

  1. The blog was absolutely fantastic! Lot of information is helpful in some or the other way. Keep updating the blog, looking forward for more content...Great job, keep it up.
    node.js development services