I am new to node js and web sockets. I am trying to create a web socket using the ws in node js.
I have two Questions:
- I do have an idea that CORS is not available for web sockets but is there a way I can still enable them?
- How I can extend the code to implement Client authentication ? Currently, I can use “wss” but I want to authenticate the client using the certificate.. How can I do that ?
Server.js Code
const { WebSocketServer } = require('ws'); const { createServer } = require('https'); const { readFileSync } = require('fs'); function startServer() { const server = createServer({ cert: readFileSync('server_cert.pem'), key: readFileSync('server_key.pem'), }); const wss = new WebSocketServer({ noServer: true }); server.on('upgrade', (request, socket, head) => { authenticate(request, (err, client) => { if (err || !client) { socket.write('HTTP/1.1 401 Unauthorizedrnrn'); socket.destroy(); return; } wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request, client); }); }); }); server.listen(7070); }
Can somebody please guide me ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I achieved CORS validation and Certificate based Client Authentication using the following Server side code:
const server = createServer({ cert: readFileSync(config.certs.sslCertPath), key: readFileSync(config.certs.sslKeyPath), ca: [readFileSync(config.certs.caCertPath)], requestCert: true, }); const wss = new WebSocketServer({ noServer: true }); server.on('upgrade', (request, socket, head) => { const origin = request && request.headers && request.headers.origin; const corsRegex = /^https?://(.*.?)abc.com(:d+)?/$/g if (origin && origin.match(corsRegex) != null) { wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request); }); } else { socket.destroy(); } });
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0