Basic Authentication in Node.js

Posted by: Mahesh Sabnis , on 1/5/2016, in Category Node.js
Views: 13811
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:

vscode-new-folder

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

//1.
var http = require('http');

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

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

};

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

    //5.
    if (!request.headers.authorization) {
        authenticationStatus (response);
        return;
    }

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

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

    //8.
    loginInfo = authentication.split(':');

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

});

//10.
server.listen(5050);

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,

http://localhost:5050

The following result will be displayed

node-basic-auth

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

auth-cancel

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

user-authenticated

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

fiddler

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

filddler-composer

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

fiddler-authenticated

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 https://github.com/jshttp/basic-auth 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.

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

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years 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). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




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

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook