A developer builds a JWT strategy in a NestJS application to secure routes. After initial testing fails due to missing cookie parsing, they install and configure cookie-parser to successfully authenticate requests. Finally, they add validation logic to ensure user email addresses remain unique during registration.
Length 11:38
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nodejs #nestjs #jwt #authentication #cookie-parser #typescript #programming #backend #api
0:00 So now we need to implement another strategy that actually validates 0:03 that JWT so that we can use this on all of our other 0:07 routes where we want to apply authentication to. 0:11 So let's go ahead and open up our auth directory again, 0:14 and let's open up and 0:15 create a new strategy in our strategies folder called 0:19 jwt.strategy.ts. So this is gonna 0:23 be a new injectable class here. 0:27 We're gonna export a class called JWTStrategy, 0:31 which will follow the same pattern as our local strategy. 0:34 We're gonna extend PassportStrategy here from 0:38 nestjs-passport. And this time we're gonna pass in the 0:41 strategy from 0:42 PassportJWT. So recall that this strategy that we 0:45 installed earlier will handle most of the work here. 0:49 We just need to supply some configuration inside of the constructor 0:52 here. So in the constructor itself, we're gonna need to get access 0:56 again to the config service here. So let's go ahead and inject the 1:00 config service as well as the user service. 1:05 So let's go ahead and inject the user service here. 1:07 And now inside of the constructor, we're gonna make a call to super here. 1:12 And now there's some options that we need to configure. 1:15 First property we're gonna configure here is JWT 1:18 from request. And what this is gonna do is it's gonna actually 1:22 specify where on the request object that the 1:26 JWT lives. So by default, this might be a header 1:29 value, but in our case, we know the JWT is actually a cookie 1:33 itself. So let's go ahead and specify that here by calling 1:37 extractJWT from passport jwt. 1:41 And then we're gonna call fromExtractors on here 1:45 and supply an array where we will 1:49 provide a function that gets the current request. 1:52 So the request object here we know will actually be 1:56 from express. So go ahead and import request
The rest of the transcript is for members.
Sign in