Basic Authentication in Node.js

Posted by: Mahesh Sabnis , on 1/5/2016, in Category Node.js
Views: 31229
Abstract: Use Basic authentication in Node.js and use HTTP headers in the request to pass user credentials.

Authentication plays a very important role in an application. The idea is to access an application, the end-user must enter a username and password. To verify the user, the application should have some mechanism.

Basic Authentication is a quick way to protect your content. The basic premise of Basic Authentication is that when used over HTTP, the password is sent as plain text. The application intercepts the header information containing Authentication information and validates the username and password by comparing it with the credential information stored at the application side e.g. Database.


Basic Authentication Implementation

Step 1: You can use any IDE of you choice. To implement this application, I will use the free Visual Studio Code. This is a new IDE used for developing and building modern Web and Cloud applications. To use Node.js built-in modules and other tools we need to use Node.js tools. Node.js can be downloaded from here.

Step 2: Create a folder with the name VSCodeBasicAuthentication on your hard drive. This folder will be used as workspace for the application. Open Visual Studio Code IDE and open the folder from File > Open Folder option. In this folder add a new folder of name Scripts as shown in the following image:


To manage Node.js intellisense for the application, run the following command from the Node.js command prompt. Open the Node.js command prompt and navigate to the VSCodeBasicAuthentication folder

npm install -g tsd
tsd query node --action install

Step 3: In the Scripts folder, add a new file with the name app.js. In this file, we will create a Web Server using http module. The following code contains logic for basic authentication

var http = require('http');

var credentials = {
    userName: "mahesh",
    password: "mahesh1234"
var realm = 'Basic Authentication';

function authenticationStatus(resp) {
    resp.writeHead(401, { 'WWW-Authenticate': 'Basic realm="' + realm + '"' });
    resp.end('Authorization is needed');


var server = http.createServer(function (request, response) {
    var authentication, loginInfo;

    if (!request.headers.authorization) {
        authenticationStatus (response);

    authentication = request.headers.authorization.replace(/^Basic/, '');

    authentication = (new Buffer(authentication, 'base64')).toString('utf8');

    loginInfo = authentication.split(':');

    if (loginInfo[0] === credentials.userName && loginInfo[1] === credentials.password) {
        response.end('Great You are Authenticated...');
    authenticationStatus (response);



The above code contains specifications as explained in following points (Note: Comment number in the above code matches with the numbering given below)

1. Create http server using http module. Here we are creating Web Server using code. This web server will be responsible for basic authentication.

2. The JavaScript object for initializing the Credentials.

3. The function authenticationStatus() is used to provide the authentication window to user when the web server url is entered in the browsers address bar.

4. The Web Server is created with the requestlistener callback.

5. This step is responsible for reading the authorization information from the header.

6. This step is responsible for filtering the ‘Basic’ word from the authorization header.

7. This step is used to decode the credential information from the header and retrieve the original values.

8. The retrieved information is in the form of userName:password. This step splits the username and password.

9. This step is used to validate the UserName and Password based on the values stored in the credentials JavaScript object. If this information is matched, then the Great You are Authenticated… message will be sent to the user.

10. Start listening on port 5050.


Step 4: Right click on the app.js and select the Open in Command Prompt. This will open the Node.js command prompt. Enter the following command from the command prompt:

Node app

Step 5: Open any browser e.g. Chrome, and enter the following URL,


The following result will be displayed


If the Cancel button is clicked then the following result will be displayed


Enter UserName as mahesh and password as mahesh1234 and the following result will be displayed:


Using Fiddler

Alternatively tools like Fiddler or Postman can also be used here to find out what is going on behind the scenes. Let’s use fiddler. Follow these steps:

1. Open Fiddler. Click on Tools > TextWizard. Enter the information as shown in the following image


2. In the Composer Tab, enter the details as shown in the following image


3. We have entered the required information. Click on Execute button, the following result will be displayed


In case you are wondering how to perform a Logout using Basic auth, just remember that basic auth applies to the current request. The browser sends authentication details every time it makes a request to the server. So a logout is not needed.

Basic Authentication using Express

You can also make your job easier by using a middleware in Express to perform basic authentication. Just explore the following url to understand how it is done.

Is Basic Authentication Secure?

Basic authentication is the most straight forward authentication mechanism and uses HTTP headers in the request to pass user credentials. However this method is insecure as it sends non-encrypted data in plain text. In a real-world scenario, if you were to use Basic authentication, use it via a secure protocol like HTTPS.

In the next article, we will see how to use Digest authentication and Token based authentication which is more secure than Basic authentication.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!