ppiatek
ppiatek

Reputation: 69

How to authenticate web sockets connection in node/ws using asynchronous function on socket upgrade event

I'm trying to authenticate WebSocket connection using this solution (server.on('upgrade',...):

https://www.npmjs.com/package/ws#user-content-client-authentication

But I need to use an async function to check the token against an external authentication service. And I have a situation where, before authentication, the ws.on('message',... event is triggered and messages are sent to the browser.

Does anyone know how to solve this?

export function initWebSocketServer( server: http.Server ) {
  wss = new WebSocket.Server({ server: server });
  wss.on('connection', connectWebSocket);

  server.on('upgrade', async function upgrade(request, socket, head) {
    socket.on('error', onSocketError);

    let res = await authenticateWebSocket(request);

    if (res === false) {
      logger.info('authenticateWebSocket > 401 Unauthorized');
      socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
      socket.destroy();
      return;
    }

    socket.removeListener('error', onSocketError);
    
    wss.handleUpgrade(request, socket, head, function done(ws) {
      wss.emit('connection', ws, request);
    });

  });  
}

function connectWebSocket(ws: WebSocket) {
  ...
  ws.on('message', (message: string) => {
    messageReceiveWebSocket( message, ws )
  });
  ...
}

Messages when a WebSocket connection is established

Upvotes: 0

Views: 51

Answers (1)

ppiatek
ppiatek

Reputation: 69

Finally I solved it using the function verifyClient, even if using it discouraged in the npm documentation (Issue #337). Only this works for me with asynchronous authentication.

Upvotes: 0

Related Questions