Chargement en cours...
Chargement en cours...
Learn how to implement a complete authentication and authorization system with NestJS
Security is a fundamental aspect of modern REST API development. In this article, we'll explore how to create a secure REST API with NestJS, implementing JWT authentication and a user role system (Admin and User).
Let's start by setting up our NestJS project. If you haven't installed the NestJS CLI yet, you can do so with the following command:
Then, let's create our project:
Let's install the necessary dependencies for our authentication system:
These packages will allow us to:
For this example, we'll use TypeORM with a PostgreSQL database. Let's install the necessary packages:
Let's configure our database connection in app.module.ts
:
Let's create a .env
file at the root of the project:
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=your_password
DB_NAME=nest_auth
DB_SYNC=true
JWT_SECRET=your_jwt_secret
JWT_EXPIRATION=3600
Let's create our User entity with role support:
Now let's create our authentication module:
Let's implement the authentication logic:
Let's create a DTO for login:
Let's create a DTO for registration:
Let's implement the users service:
Now, let's implement our role-based access control system. First, let's create a JWT strategy:
Let's create a custom guard to check roles:
Let's create a decorator to specify required roles:
Let's configure the authentication module:
Let's configure the users module:
Now, let's implement the controllers with protected routes:
Let's create the decorator to get the current user:
Let's create the controller for users with role-protected routes:
Let's configure global validation in our application:
Let's create a custom exception filter:
Let's apply this filter globally:
In this article, we created a secure REST API with NestJS, implementing JWT authentication and a role-based access control system. We have:
This model can be extended to meet more complex needs, such as adding features like:
The complete code is available on GitHub.