Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side websocket certificate in NodeJS

I have a NodeJS websocket client app, using ws https://www.npmjs.com/package/ws - this NodeJS app connects as a client to a websocket server.

I can use HTTPS by specifying wss:// as the protocol.

How can I make the TLS connection use a client certificate for authentication?

i.e. the websocket client should use a certificate to prove its identity to the server.

like image 804
fadedbee Avatar asked Oct 16 '22 10:10

fadedbee


1 Answers

I found:

it('connects to secure websocket server with client side certificate', function(done) {
  const server = https.createServer({
    cert: fs.readFileSync('test/fixtures/certificate.pem'),
    ca: [fs.readFileSync('test/fixtures/ca1-cert.pem')],
    key: fs.readFileSync('test/fixtures/key.pem'),
    requestCert: true
  });

  let success = false;
  const wss = new WebSocket.Server({
    verifyClient: (info) => {
      success = !!info.req.client.authorized;
      return true;
    },
    server
  });

  wss.on('connection', () => {
    assert.ok(success);
    server.close(done);
    wss.close();
  });

  server.listen(0, () => {
    const ws = new WebSocket(`wss://localhost:${server.address().port}`, {
      cert: fs.readFileSync('test/fixtures/agent1-cert.pem'),
      key: fs.readFileSync('test/fixtures/agent1-key.pem'),
      rejectUnauthorized: false
    });
  });

});

on https://github.com/websockets/ws/blob/14d9088391ac4495d04e64d76c3b83d4e75f80e2/test/websocket.test.js

like image 67
fadedbee Avatar answered Oct 20 '22 16:10

fadedbee