Wednesday, December 7, 2016

NodeJS Tutorial 5: Using HTTPS with Express

NodeJS Tutorial 5

Using HTTPS with Express

NodeJS Tutorial 5: Using HTTPS with Express

Tutorial 5: Using HTTPS with Express
Tutorial 6: Develop a JSON API server
Tutorial 7: Use Templates and Views with Express
Tutorial 8: Integrating MongoDB
Tutorial 9: Testing Express Applications
Tutorial 10: Securing Express

To make end to end secure communication, you need HTTPS. To a great extent it protects data packets from intercepting by third party tools. HTTPS i.e. HTTP communication over SSL(Secure Socket Layer) or TLS(Transport Layer Security).

If you don't  understand these terms, don't worry. In layman terms, HTTP and HTTPS works in a same fashion except the data communication between web browser and web server is encrypted which prevents man-in-middle snooping. Both web server and browser have in-built mechanism to encrypt and decrypt the data and for this web server keeps an SSL certificate. This SSL certificate is issued by Certifying Authorities (CA) and the browser uses this certificate (public-key) to verify the identity of the web server.

In nutshell, you need SSL certificate which you can obtain in the following three ways:

1. Generate your own self-signed certificate.
2. Obtain a free certificate from free CA
3. Buy a commercial certificate.

1. Self-signed certificate is required for development or testing purpose. This certificate is not used for commercial purpose. You can generate your own using openssl tool on a Linux environment. Tony Erwin blog has a nice post that provides steps to create self-signed certificate using openssl. Alternately you can go to websites like MakeCert or www.selfsignedcertificate.com.

2. There are certifying authorities that offer free SSL production-ready certificates like CACert  and LetUsEncryt. There are “ifs and buts” are involved to issue certificates from these organizations, but they are gaining popularity. There are other organizations which offer 30 days to 90 days valid certificates on trial.

3. Companies like Verisign, GoDaddy, BigRock, Bluehost and may other hosting sites vendors sell SSL certificates for few hundreds to a few thousand dollars.

Using certificates in ExpressJS



SSL certificates are available in various packaged file formats. (e.g. .pem, .key, .cer, .der file extensions). Go to website SelfSignedCertificate.com, fill up the server name as 'localhost' and click on 'Generate' button.
NodeJS Tutorial 5: Using HTTPS with Express


It will generate two files viz. localhost.key and localhost.cert. Download these files and save under a 'certs' folder. Make sure the 'certs' folder exists from where you run your nodejs program. Also ensure the name of files must be 'localhost.key' and 'localhost.cert'.

NodeJS Tutorial 5: Using HTTPS with Express


Let us write a simple HTTPS based expressJS server that listens on port 443 (default ssl port).

var https = require('https'); 
var fs = require('fs'); 

var express = require('express'); 
var app = express(); 

var options = { 
 key: fs.readFileSync(__dirname + '/certs/localhost.key'), 
 cert: fs.readFileSync(__dirname + '/certs/localhost.cert') 
}; 

https.createServer(options, app).listen(443, function(){ 
 console.log('Express started and running on port 443'); 
}); 

app.use(express.static(__dirname + '/public')); 
app.use(function(req, res) { 
 res.status(404); 
 res.send("File not found!"); 
}); 


We need https module and path of certificate files (here initialized as variable 'options'). https.createServer requires two parameters i.e. express module instance and  options to run it. Run the nodejs file. You might have to run  the nodeJS program in sudo mode, in case port 443 requires admin privileges.

NodeJS Tutorial 5: Using HTTPS with Express


Open a browser (e.g. Firefox) and type url as 'https://localhost', you will get a warning message that this connection is untrusted (because of self-signed certificate).  Click on 'I Understand the Risks' and then click on 'Add Exception' button.


NodeJS Tutorial 5: Using HTTPS with Express

A dialog will pop-up to accept and confirm security exception for the self-signed certificate.  Click on 'Confirm Security Exception' button. For a production-ready SSL certificate (e.g. For a website domain), this security exception should not come.

NodeJS Tutorial 5: Using HTTPS with Express

Now you can see the webpage hosted on localhost.

NodeJS Tutorial 5: Using HTTPS with Express


You can click on 'lock' icon on the url-bar and check the SSL certificate details.

If you try to run http://localhost, it will time out. You can run  both  httpp and https server simultaneously. The following snippet (ex13.js) shows this.

var http = require('http');
var https = require('https');
var fs = require('fs');

var express = require('express');
var app = express();

var options = {
 key: fs.readFileSync(__dirname + '/certs/localhost.key'),
 cert: fs.readFileSync(__dirname + '/certs/localhost.cert')
};

https.createServer(options, app).listen(443, function(){
 console.log('HTTPS Express started and running on port 443');
});

http.createServer(app).listen(8000, function(){
 console.log('HTTP Express started and running on port 8000');
});

app.use(express.static(__dirname + '/public'));
app.use(function(req, res) {
 res.status(404);
 res.send("File not found!");
});

In the next tutorial let us explore the concept of micro-services and design a simple JSON API server.


No comments: