【问题标题】:NestJs socket authentication, emit event in handleConnectionNestJs套接字身份验证,在handleConnection中发出事件
【发布时间】:2021-07-26 05:12:57
【问题描述】:

身份验证失败后,在断开连接之前,我想向客户端发出一个事件,通知请求提供的令牌无效。在我的 WebSocketGateway 这是我的代码:

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

我的客户:

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

未发送/接收事件。有什么想法吗?

干杯

【问题讨论】:

  • socketAuthService.authenticate 同步吗?
  • 是的,它是同步的
  • 你使用了保护。或者控制台所有Client disconnected due to invalid token:可能是你的客户端在函数handleConnection运行之前断开了
  • 不,它已连接,直到我断开客户端。该事件根本没有发出。我使用allowFunction() 对问题进行了排序。我更喜欢这个想法,因为它甚至不让套接字连接,我不喜欢的是它不允许我抛出 401,而是发送一个 CORS 错误

标签: socket.io nestjs nestjs-gateways


【解决方案1】:

您需要使用自定义套接字错误代码和消息关闭套接字。您可以通过使用 socket.close(code, message); 来做到这一点;

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

你会得到这样的异常 Postman exception on websockets invalid origin

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2021-02-12
    • 2021-01-13
    • 2019-09-05
    • 2018-11-02
    • 2019-03-28
    • 2014-04-21
    • 2014-12-25
    • 2019-04-14
    相关资源
    最近更新 更多