NodeJS中的客户端Websocket证书

时间:2018-11-29 15:25:11

标签: node.js ssl websocket client-certificates ws

我有一个ws https://www.npmjs.com/package/ws使用的NodeJS Websocket客户端应用程序-该NodeJS应用程序作为客户端连接到Websocket服务器。

我可以通过指定wss://作为协议来使用HTTPS。

如何使TLS连接使用客户端证书进行身份验证?

即websocket客户端应使用证书向服务器证明其身份。

1 个答案:

答案 0 :(得分:1)

我发现:

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
    });
  });

});

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