NodeJS - Setting up NodeJS with SSL (Self-Signed Certificate)

Below is a one page guide to setup a NodeJS server with SSL (Self-Sign Certificate)

1) Assuming you have NodeJS installed, write a following NodeJS application (see https://nodejs.org/dist/latest-v10.x/docs/api/https.html).

For me, I had written it at /tmp/nodejsapp/app_https.js

const https = require('https');
const fs = require('fs');
const options = {
  key: fs.readFileSync('keys/key.pem'),
  cert: fs.readFileSync('keys/certificate.pem')
};
https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);
Note the key and cert location. That will be the directory relative to your NodeJS application. For me, it will be /tmp/nodejsapp/keys

2) You need to generate a self signed certificate with openssl

openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem
Answer the prompt and the above command will generate a key.pem and certificate.pem.

You can verify the certificate with

 openssl x509 -text -noout -in certificate.pem

See https://www.ibm.com/support/knowledgecenter/en/SSWHYP_4.0.0/com.ibm.apimgmt.cmc.doc/task_apionprem_gernerate_self_signed_openSSL.html

Then, move the key.pem and certificate.pem to the location referenced by the NodeJS key and cert options. For me, that will be /tmp/nodejsapp/keys

3) Run NodeJS with

node app_https.js

4) Test the HTTPS with

curl -k -vvv https://:8000

or from browser



Comments

Popular Posts