A developer implements role-based access control by modifying a user DTO and schema, creating a custom roles decorator, and updating a JWT authentication guard. The process includes testing with API requests in an IDE to verify route protection and authorization logic.
Length 8:37
Captions English (Generated), Spanish (Auto-translated), French (Auto-translated), Korean (Auto-translated), Portuguese (Auto-translated), Vietnamese (Auto-translated) #nestjs #authentication #authorization #roles #middleware #decorators #typescript #backend #api #guard
0:00 Okay, so I want to show you how we can easily 0:02 add role 0:03 functionality to our authentication and users right now, so 0:07 that we can provide different roles to our users and ensure that only 0:11 users with those roles can access certain routes in our system. 0:14 So the first step in this will be going into auth 0:18 and going to the user DTO. In the create 0:22 user DTO, we're now going to accept, in addition to an email 0:26 and password, we're also going to accept an array of 0:29 roles that a 0:31 user can pass in. So this will be an optional parameter, 0:34 which will just be 0:35 a array of strings, and we'll provide an is optional decorator 0:39 from class validator to mark this as optional so 0:43 that if it's not provided, it won't apply the rest of our validators. 0:47 Otherwise, we're gonna make sure that this is an array, and then we'll call 0:51 the is string validator to make sure that each value is a 0:55 string. And to make sure each value is validated here, 0:59 we will call each, which satisfies if the validated value is an 1:03 array. Each of the s- items must be validated, which 1:06 is what we want. 1:07 So each item will be a string, and importantly, we can also say 1:10 is not empty for each value to make sure that 1:14 the empty string is not provided. So in addition to our 1:18 DTO, let's go ahead and copy this property, the 1:22 roles property, and add it to our user model, 1:25 which we know 1:26 lives in 1:27 libs/common/src/models/user.schema. 1:32 Let's go ahead and add this roles property to the actual 1:35 schema here by calling addProp. 1:39 Finally, we'll update the common user DTO to add 1:43 the 1:43 new roles array. 1:45 So I have my containers running in the background. 1:47 I ran Docker Compose up, and now let's try creating a
The rest of the transcript is for members.
Sign in