Self-signed certs with secure WebSockets in Node.js
First generate your self-signed certs:
|
1 |
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 100 -nodes |
Then create your httpsServer from an express app using node’s built-in https server:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var privateKey = fs.readFileSync('sslcert/key.pem', 'utf8'); var certificate = fs.readFileSync('sslcert/cert.pem', 'utf8'); var credentials = {key: privateKey, cert: certificate}; var express = require('express'); var app = express(); //... bunch of other express stuff here ... //pass in your express app and credentials to create an https server var httpsServer = https.createServer(credentials, app); httpsServer.listen(8443); |
Then setup your websocket server (ironically this will use the same port as the http server, I didn’t know this but I guess protocols can share ports? — this had me going for awhile).
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({ server: httpsServer }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); ws.send('something'); }); |
Now browse to https://0.0.0.0:8443 server and accept the self-signed cert in Chrome. Then websockets should now work isnide the browser.
Open a chrome devtools console and type:
|
1 2 |
var ws = new WebSocket('wss://0.0.0.0:8443'); ws.send('foo'); |