NestJs socket authentication, emit event in handleConnection

4.2k views Asked by At

Upon failed authentication, before disconnecting, I want to emit an event to the client informing that the token provided with the request is invalid. In my WebSocketGateway this is my code:

 handleConnection(client: Socket, ...args: any[]) {
        try {
            this.socketAuthService.authenticate(client);
            this.logger.log(`Client connected: ${client.id}`);
        } catch (e) {
            this.logger.error(`Client ${client.id} tried to connect with invalid token`);
            client.emit('unauthorized', 'Invalid Token');
            client.disconnect();
            this.logger.log(`Client disconnected due to invalid token: ${client.id}`);
        }
    }

My client:

this.socket.on('unauthorized', (msg) => {
  console.log(msg);
});

The event is not sent / received. Any idea?

Cheers

1

There are 1 answers

0
Hassan On

What you need is to close the socket with a custom socket error code and a message. You can do this by using socket.close(code, message);

socket.close(4004, "Unauthorized Request");

You will get an exception like this Postman exception on websockets invalid origin