Nodejs TLS configuration server and client example
This is a simple walk through for configuring TLS(Transport Layer Security) version in a nodejs server and client. The nodejs server can restrict which secure protocol is not accepted, and the client can choose which secure protocol to use when making a request to a server. For example, if a server does not allow TLS1.0 and TLS1.1, then the client has to use TLS1.2
1. To create a https server, a certificate is needed. Run the following from the command line to generate self-signed certificate.
openssl genrsa -out key.pem openssl req -new -key key.pem -out csr.pem openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
2. Create server file, my_server.js
const https = require('https'); const fs = require('fs'); const constants = require('crypto').constants; const hostname = '127.0.0.1'; const port = 8000; const options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem'), requestCert: false, rejectUnauthorized: false, secureOptions: constants.SSL_OP_NO_SSLv2 | constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_TLSv1 //| constants.SSL_OP_NO_TLSv1_1 }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(port, hostname, () => { console.log(`Server running at https://${hostname}:${port}/`); });
3. Create client file, my_client.js
const https = require('https') // possible values for secureProtocol: https://www.openssl.org/docs/man1.1.1/man7/ssl.html#Dealing-with-Protocol-Methods // const protocol = "TLSv1_1_method" const protocol = "TLSv1_2_method" const options = { hostname: '127.0.0.1', port: 8000, method: 'GET', secureProtocol: protocol, rejectUnauthorized: false } https.request(options, res => { let body = '' res.on('data', data => body += data) res.on('end', () => { console.log('response data: ' + body) }) }).on('error', err => { console.warn(err) }).end()
4. Run the server file from command line.
node my_server.js
5. Open another command line window and run the client file.
node my_client.js
6. Stop the server by Ctrl-c, and update the value for secureOptions in the my_server.js and the value for protocol in the client, and see the how it behaves.
7. For example, uncomment this //| constants.SSL_OP_NO_TLSv1_1
for the secureOptions in the my_server.js means, the server will not accept TLS1.1 protocol. Setting the protocol = "TLSv1_1_method"
means making the request using the TLS1.1 protocol.
Search within Codexpedia
Search the entire web