Wednesday, May 6, 2015

Basic Authentication with Node.js Request Module


I am working on a demo with Feedhenry and Data Virtualization which will be in a larger blog later.  But I wanted to highlight a portion of it this week.  In the Node.js cloud application I am using the Node.js request module to make a call with Basic Authentication to a Virtual Database to retrieve data from a MySQL Datasource.  So below I wanted to cover the following concepts:
  1. What is Basic Authentication
  2. How to use the Node.js Request Module
  3. How to use Basic Authentication with the Node.js Request Module
  4. Some resources
What is Basic Authentication?

HTTP supports the use of several authentication mechanisms to control access to pages and other resources. These mechanisms are all based around the use of the 401 status code and the WWW-Authenticate response header.

The most widely used HTTP authentication mechanisms are:
  • Basic - The client sends the user name and password as unencrypted base64 encoded text. It should only be used with HTTPS, as the password can be easily captured and reused over HTTP.
  • Digest - The client sends a hashed form of the password to the server. Although, the password cannot be captured over HTTP, it may be possible to replay requests using the hashed password.
  • NTLM  - This uses a secure challenge/response mechanism that prevents password capture or replay attacks over HTTP. However, the authentication is per connection and will only work with HTTP/1.1 persistent connections. For this reason, it may not work through all HTTP proxies and can introduce large numbers of network roundtrips if connections are regularly closed by the web server.

Basic authentication is the most prevalent HTTP authentication protocol. Almost every major client and server implements basic authentication. Basic authentication was originally described in the HTTP/1.0 specification, but it has since been relocated into RFC 2617, which details HTTP authentication.

In basic authentication, a web server can refuse a transaction, challenging the client for a valid username and password. The server initiates the authentication challenge by returning a 401 status code instead of 200 and specifies the security realm being accessed with the WWW-Authenticate response header. When the browser receives the challenge, it opens a dialog box requesting the username and password for this realm. The username and password are sent back to the server in a slightly scrambled format inside an Authorization request header.

How to use the Node.js Request Module?

In any application framework one basic need is to be able to make REST calls overHTTP/HTTPS, they are widely used and very useful in cases of API interactions and web scraping. We can use the Node.js core modules http or https to perform these calls but that that can be a cumbersome process and the Request module makes it simple to perform these HTTP requests. In this tutorial we will learn about how to get started with the request module to perform HTTP calls.
The callback function contains three parameters:
  • Error: This is the first parameter of the callback function. It will be null in case there is no error or it will contain the error object with appropriate details. You should always check for the error before continuing to process the response.
  • Response: This is the second parameter in the callback function. This contains the http.IncomingMessage object which contains additional data about the http/https request i.e status code, headers, etc.
  • Body: This is the third parameter and contains the body of the http/https response. This is a string type containing the contents of the body if the response is in text format, the body is a buffer if the response data is in the binary / octet streamencoding, finally the body will be a JSON object if the response is in JSON encoding.

The Request module has some shortcut methods for making calls in common REST methods like POST, PUT or DELETE, these notations are as follows:

  • request.post is for POST request.
  • request.put is for PUT request.
  • request.delete is for DELETE request.
  • request.post is for GET request.
  • request.patch is for PATCH request.

By default the request module makes a GET request, if not specified explicitly. Alternatively, we can also use request.get, using request.get makes the code more readable.

How to use Basic Authentication with the Node.js Request Module?

Below is an easy way to use basic authentication while using the request library for Node.js.


The request does not come with a parameter you can use, so you need to provide it by yourself. The common way is to add it as an extra HTTP header. As you can see in the code below the request module is added.  The header is then constructed.

The Authorization header is constructed as follows:
  • Username and password are combined into a string "username:password"
  • The resulting string is then encoded using the RFC2045-MIME variant of Base64, except not limited to 76 char/line
  • The authorization method and a space, i.e. "Basic " is then put before the encoded string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var username = "user";
var password = "password";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
    
function helloRoute() {
  var hello = new express.Router();
  hello.use(cors());
  hello.use(bodyParser());
  
   //GET REST endpoint
  hello.get('/',function(req, res) {
    console.log(new Date(), 'In hello route GET / req.query=',req.query);
    var url = 'http://jbossdv61-ossmentor.rhcloud.com/odata/test.1/test.SvcView?$format=JSON';
    
    console.log(new Date(), 'calling Data Virtualization', url);
    
    request.get( {
        url : url,
        headers : {
            "Authorization" : auth
        }
      }, function(error, response, body) { res.json({msg: body }); console.log(body);
      
      } );
  } );

References:
http://www.httpwatch.com/httpgallery/authentication/
http://www.codeproject.com/Articles/149738/Basic-Authentication-on-a-WCF-REST-Service
https://www.safaribooksonline.com/library/view/http-the-definitive/1565925092/ch12s02.html
http://blog.modulus.io/node.js-tutorial-how-to-use-request-module
http://www.haykranen.nl/2011/06/21/basic-http-authentication-in-node-js-using-the-request-module/
http://en.wikipedia.org/wiki/Basic_access_authentication