Basic Authentication in Node.js with Http-Auth

Follow the instructions below to run a simple web server that requires a test user to log in using a password, which is then checked against a text file that contains encrypted passwords for each user of the system.

This example uses the “basic” authentication method, which means that the user’s password may be sent over the network in plain text unless a supplementary form of encryption, like HTTPS, is used. For a similar example that uses “digest” authentication to get around this problem, see the next post.


1. If you have not already done so, download and install Node.js.

2. In any convenient location, create a new directory named “AuthenticationTest”.

3. Open a command prompt session and navigate to the newly created AuthenticationTest directory.

4. In the command prompt, run the following commands and verify that the installation completes with no errors.

npm install http
npm install http-auth

5. Still in the command prompt, run the following commands and verify that they complete with no errors. The commands install a password-setting utility and use that utility to create a new user named “MyUsername” with the password “MyPassword”. This username and an encrypted version of the password are stored in a file named “htpasswd”.

npm install -g htpasswd
htpasswd -bc htpasswd MyUsername MyPassword

6. In the AuthenticationTest directory, create a new text file named “AuthenticationServer.js”, containing the following text:

var http = require("http");
var http_auth = require("http-auth");

var hostAddress = ""; // localhost
var portNumber = 1337;

var authenticatorBasic = http_auth.basic
		file: __dirname + "/htpasswd"

var server = http.createServer
	function (request, response)
			200, // OK
			{"Content-Type": "text/plain"}
		response.write("Welcome, " + request.user + "!");

server.listen(portNumber, hostAddress);

	"Server running at http://" 
	+ hostAddress + ":" 
	+ portNumber + "/"

7. In the command prompt, run the following command. Leave the window open and the program running.

node AuthenticationServer.js

8. Open a web browser and navigate to “localhost:1337”. Enter the username and password specified in a previous step (“MyUsername” and “MyPassword”). Verify that a message is displayed greeting the user by name.

This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s