A technical tutorial demonstrating how to implement JWT authentication in a NestJS backend. The process involves configuring cookie-parser middleware, creating a JWT strategy for Passport, implementing an AuthGuard, and testing protected routes with Postman to ensure valid session handling and secure user authentication.
Length 10:21
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nestjs #jwt #authentication #middleware #cookie-parser #typescript #web-development #programming #postman #backend
0:00 Okay, so the first step in actually being able 0:02 to receive our JWT cookie 0:04 on our backend for subsequent authentication, we need to actually 0:08 be able to parse incoming cookies. 0:10 To do this, we're gonna utilize the cookie-parser 0:13 library, which allows 0:14 us to parse incoming cookies on a request, and it will 0:18 automatically populate the cookies object on the 0:22 incoming request with any cookies. 0:24 So this makes working with cookies a lot easier. 0:28 In Shoppy backend, I'll go ahead and pnpm install 0:31 cookie-parser. 0:35 And then we'll also go ahead and install as development dependency 0:38 type/cookie-parser. 0:43 So now that we have cookie-parser, go back to your main.ts 0:47 file, and now we can actually invoke 0:49 cookie-parser 0:51 as middleware. So middleware is just code that's always going to 0:54 run before any request, and we can do things like 0:58 parse incoming cookies and mutate the current 1:02 request object, which is exactly what we wanna do. 1:06 So in order to register this middleware, we're gonna call 1:09 app.use, which is gonna allow us to apply 1:11 middleware to every 1:13 single route in our system at once, which is just what we want. 1:17 Then I'll supply the cookie-parser middleware here, and we 1:20 import cookieParser from cookie-parser. 1:24 All right, so with cookie-parser in place, we're now actually gonna be able to 1:27 parse incoming cookies and have them set automatically on our 1:30 request 1:30 object, which is great because now we can read the 1:33 incoming JWT 1:34 cookie. Let's go ahead and actually implement the JWT 1:38 strategy now, which is what we're gonna utilize to 1:41 authenticate 1:42 with a JWT opposed to our user's credentials. 1:46 So in the strategies folder, I'll create a new 1:49 jwt.strategy.ts. 1:53 Now, just like the local strategy, this will again be an 1:57 injectable class from Nest common. 2:00 We'll go ahead and export this class 2:02 JWTStrategy 2:05 that will extend Passport strategy, just as we've done
The rest of the transcript is for members.
Sign in