0:00 Okay, so let's go ahead and implement authentication for our 0:03 GraphQL WebSockets so that a client is always gonna 0:07 provide us with a valid JWT or JSON Web Token 0:11 that they, of course, acquired when logging in, so that only authorized 0:15 users can actually establish a WebSocket connection with our back 0:19 end. 0:20 So let's go into our back end and into the 0:24 app.module. We're gonna go ahead and configure GraphQL 0:27 WS to actually authenticate that JWT, 0:31 and then populate the current user object on the 0:36 execution context, so we can use it later on to determine 0:40 if we want to show this user a, a new message. 0:44 For example, if we're sending messages, we don't wanna show those messages 0:48 to ourselves, so we don't get duplicates, for example. 0:53 So in order to configure GraphQL WS, we can open up 0:57 an options object, and in here, we have an onConnect 1:01 function, which is a callback that will be called when the client 1:05 requests the connection. 1:07 And so this function gets the execution context passed to it. 1:11 So we'll type it as any. And now I want to go ahead and 1:15 pull off the JWT on the incoming request, 1:19 which we can use the context for 1:22 to determine if the user is authenticated. 1:25 Now, we're not gonna be able to use cookie 1:27 parser like we're using in our 1:29 main.ts for other HTTP routes, because 1:33 it's only going to work on normal HTTP routes. 1:37 In ex- this case, with this GraphQL WebSocket connection, 1:40 we need 1:41 to actually pull off the JWT cookie manually. 1:46 So let's go ahead and do just that. I'll open up a try catch block, 1:50 because if any errors are thrown during this process, 1:53 I simply want to 1:54 throw an unauthorized exception. 1:56 So we're gonna go ahead and create a new const to represent the
The rest of the transcript is for members.
Sign in