0

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

user3353167
  • 782
  • 2
  • 16
  • 31
  • is `socketAuthService.authenticate` synchronous? – Micael Levi May 03 '21 at 19:59
  • yeah it is synchronous – user3353167 May 03 '21 at 20:13
  • did you use guard. Or console all `Client disconnected due to invalid token:` May be your client is disconnect before function handleConnection run – Kien Nguyen Ngoc May 06 '21 at 05:51
  • nope it's connected, until I disconnect the client. The event is simply not emitted. I kinda sorted the issue by using allowFunction(). I like the idea more because it doesn't even let the socket connected, what I don't like is that instead of allowing me to throw a 401 it sends a CORS error – user3353167 May 08 '21 at 16:25

1 Answers1

1

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

Hassan
  • 41
  • 4