0

In order to implement manually an authentication process with websockets in NestJS, I'm using a NestJS Gateway but have troubles setting up a handler for the "upgrade" http request that is sent during the handshake before the connection of the websocket. Is there a way to set up somewhere a function that can enable me to catch this request so I can deny access asap?

This would allow to stop the process sooner and that no socket can be opened if there is no valid auth token in the http request. I found that I can validate the socket aftewards using the protocol field of a websocket instance (the client just sets a second parameter on websocket connection), but I prefer not having to deal with "bad" sockets to close just after their connection and stop them on the initial handshake through http, whatever the process.

zenbeni
  • 7,019
  • 3
  • 29
  • 60

1 Answers1

1

The best example I have seen of doing this is here: https://github.com/mauricekraus/nestjs-ws-wrapper

Note that the example works, but the package seems to be missing some dependencies in package.json.

He is authenticating with a JWT, but I believe you could adapt the approach easily enough.

From the description:

This project tries to prevent a websocket connection from being established if a user is not properly authenticated (before the connection event, but on upgrade).

And under Usage

Just inherit from the base class (SocketGateway) and if you want to have your sockets authenticated, create an init method and decorate it with @SocketInit() and call the authentication method.

@SocketInit()
  public initTest(request: IncomingMessage) {
    return this.authenticate(request);
  }
Bill Kidwell
  • 280
  • 2
  • 9