a blog for those who code

Tuesday 20 October 2015

Implement Basic Authentication in NodeJS

In this post we will be discussing about implementing basic authentication in Node.js and how to process a Basic Authentication request over plain HTTP. Basic authentication is a method for a HTTP user agent to provide user name and password when making a request. Basic authentication is a quick and efficient way to protect your content.

Example of Basic Authentication

var http = require('http');

var username = 'codingdefined',
    password = 'coding',
    realm = 'Coding Defined';

http.createServer(function (req, res) {
  var auth, login;

  if(!req.headers.authorization) {
    authenticateResponse(res);
    return;
  }
  auth = req.headers.authorization.replace(/^Basic /, '');
  auth = (new Buffer(auth, 'base64').toString('utf8'));
  
  login = auth.split(':');

  if(login[0] === username && login[1] === password) {
    res.end("Login Successful");
    return;
  }
  authenticateResponse(res);
}).listen(8052);

function authenticateResponse(res) {
  res.writeHead(401, {'WWW-Authenticate' : 'Basic realm="' + realm + '"'});
  res.end('Authorization required');
}

In the above code at first we are checking that response object has Authorization header or not. If it is not present browser's login dialog blocks any further content from being loaded in the browser, until the users either attempts to log in or cancels it. If the user cancels it, the user will see a message "Authorization required" in the browser.


If user tried to log in, browser will send another response to the server with Authorization header. If the authorization header is present we will only extract base64 encoded username:password string sent from client. After that we will decode the base64 to utf8 and check if the username and password is correct or not. If the username and password match our stored cresentials, the user is granted access and he will see "Login Successful" message.

No comments:

Post a Comment