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
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);
You will get an exception like this Postman exception on websockets invalid origin