Thursday, October 30, 2014

nodejs - secured server with https connections

Previous post


Checkout the code at github
If you can use command below for checkout and run the app.

vanduc@VGN-FZ290E:~/test2$ git clone --depth=10
vanduc@VGN-FZ290E:~/test2$ cd nodejs-example/
vanduc@VGN-FZ290E:~/test2/nodejs-example$ git checkout -f 4-https
vanduc@VGN-FZ290E:~/test2/nodejs-example$ npm install
vanduc@VGN-FZ290E:~/test2/nodejs-example$ node index.js

HTTPS configuration 

For configuration HTTPS connection we need a key and self signed certification to make the SSL work.

Creating key/certificate pair very easy with only one line, if you already installed OpenSSL

openssl req -subj '/CN=localhost/O=mycompany/C=VN' -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout server.key -out server.crt

Code for HTTPS connection:

var options = {
  key: fs.readFileSync('./ssl/server.key'),
  cert: fs.readFileSync('./ssl/server.crt')
var server = https.createServer(options,app).listen(serverConfigure.sslPort, function () {
 var address,
        host = ? : 'localhost',
        port = serverConfigure.sslPort;
    address = host + ':' + port;
    console.log('HTTPS server is listenning on localhost:3443');

We will create HTTPS server by add option, the option is about the path of key and certificate,
the server will create with the option for SSL connection , express server by app variable.

HTTPS auto redirection

In order to protect our server (users still can access our server by HTTP connection). We need to redirect the user request to HTTPS connection.

There is some ways to make HTTP auto redirection
  1. inside nodejs code.
  2. configure firewall to auto forward.
We can simply configure inside nodejs code

function requireHTTPS(req, res, next) {
    if (! {
        var addressSSL,
            host = ? : 'localhost',
            port = serverConfigure.sslPort;
        addressSSL = host + ':' + port;
        return res.redirect('https://' + addressSSL + req.url);
if (serverConfigure.httpsAutoRedirection) {

If the option httpsAutoRedirection in serverConfigure file is true,  we will check every request to the server and redirect the request to HTTPS port.