【问题标题】:Nestjs wss handleConnection(socket) socket.handshake is undefined and cannot access headers to authenticateNestjs wss handleConnection(socket) socket.handshake 未定义,无法访问标头进行身份验证
【发布时间】:2021-06-19 07:45:30
【问题描述】:

我有一个 Nestjs 网关,我尝试根据标头中的值运行授权逻辑,但无论我尝试访问握手,它总是返回“未定义”

我也在通过 SSL 尝试这个,这可能会有所作为。

main.ts:

    import { WsAdapter } from "@nestjs/platform-ws";

    app = await NestFactory.create(UserMicroserviceModule, {
      httpsOptions: {
        key: get_ssl("key"),
        cert: get_ssl("cert"),
      },
    });

    app.useWebSocketAdapter(new WsAdapter(app));
    await app.listen(process.env.PORT || 443);

gateway.ts:

@UseGuards(SessionGuard)
@WebSocketGateway({ path: "/user" })
export class UserMicroserviceGateway implements OnGatewayConnection {

  handleConnection(socket) {
     socket.handshake // <== undefined
  }

session.guard.ts:

    const socket_cookie: any = context.switchToWs().getClient().handshake; // <== undefined

而且,虽然我已经在整个网关上添加了会话保护 --- 保护不会为 handleConnection() 触发

【问题讨论】:

    标签: node.js websocket nestjs ws nestjs-gateways


    【解决方案1】:

    Guards 和其他装饰器目前不适用于nestjs 中的 handleConnection() 方法,握手不是 vanilla socket 上存在的概念,而是更多 socket.io 的东西,所以我只是切换到使用它并在 handleConnection() 方法中手动运行验证所需的操作。

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 2016-01-11
      • 2019-04-09
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多