A developer demonstrates how to secure WebSocket connections in a NestJS gateway using JWT authentication. The walkthrough covers implementing the handle connection lifecycle method, updating auth services, creating server actions for token retrieval, and configuring client-side Socket.IO connections with proper authentication headers.
Length 6:49
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nestjs #socket.io #authentication #jwt #typescript #gateway #webhooks #web development #coding
0:01 All right, so next up I wanna show you how we can 0:03 apply authentication to our 0:04 WebSocket connection to ensure that only authenticated users who are 0:08 logged in and have a valid JWT can establish a 0:12 connection to our backend over the WebSocket gateway. 0:16 Let's open up our products gateway again. 0:20 So the NestJS gateway implements a 0:24 method called handle connection. 0:28 So handle connection is called whenever a new connection 0:32 is received by this gateway. NestJS will automatically 0:36 call this handle connection method, and it'll also pass 0:39 it the client socket object, in our case, from 0:44 Socket.IO. 0:46 So what I wanna do is pull off the JWT off this incoming 0:50 client socket, which we can pass on our Next.js UI. 0:54 Let's go ahead and wrap this in a try-catch block 0:59 and catch any errors. So in the try, I now want to use 1:03 our JWT service to actually verify the incoming 1:06 token. So to do this, I'll go back to our auth service 1:11 and let's add a new method in here called verify 1:15 token. So we'll have verify token that gets passed in 1:20 a JWT of type string, 1:23 and we'll simply call 1:25 this.jwtservice.verify and pass 1:29 in that JWT. 1:31 So now we have a public method on our auth service we can use to verify our token. 1:36 Let's go back into our products gateway and add a constructor, 1:40 so we can go ahead and inject the auth service now. 1:44 So with the auth service, let's now call this 1:47 function 1:49 this.authservice.verifytoken 1:53 and pass in... Well, now we need to pass in the JWT on this 1:56 incoming client socket. So we can access 1:59 client.handshake, which is an object that we're 2:03 able to provide on our client side connection, 2:07 where we can provide things like 2:10 an auth object. So inside of here we have a dedicated auth
The rest of the transcript is for members.
Sign in