In this post we will review the steps required to configure SSL for express server on NodeJS.
Unlike many other articles, this post includes BOTH the code changes, and the keys creation steps.
This is intended for development environment, hence we will use a self signed certificate.
Create the Keys
We will create a Certificate Authority (CA) key and certificate, and then we will create a server key and certificate.
rm -rf ./ssl
mkdir ./ssl
sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=" -keyout ./ssl/key.pem -out ./ssl/cert.pem
sudo openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=" -keyout ./ssl/ca.key.pem -out ./ssl/ca.pem
sudo chmod -R 777 ./ssl
The NodeJS SSL Server
The following runs both HTTP and HTTPS servers.
If required, the related HTTP listener can be removed.
const express = require('express')
const fs = require('fs')
const cors = require('cors')
const https = require('https')
const app = express()
app.use(express.static('public'))
app.use(cors())
app.get('/', (req, res) => {
res.json({msg: 'OK'})
})
app.listen(8080)
const options = {
key: fs.readFileSync('/etc/ssl/key.pem'),
cert: fs.readFileSync('/etc/ssl/cert.pem'),
ca: fs.readFileSync('/etc/ssl/ca.pem'),
}
https.createServer(options, app).listen(8443)
No comments:
Post a Comment