Building an Authentication and Authorization System with NestJS
In modern web development, security is a priority. One of the key aspects to ensure secure applications is implementing a solid authentication and authorization system. In this post, I will guide you through the development of a powerful authentication and authorization system built with NestJS, covering all essential features such as user registration, role-based access control, OAuth2 support, and multifactor authentication (MFA).
Key Features of the System
-
User Registration (Signup)
- Users can create an account by filling out a registration form.
- Data validation and email confirmation are integrated to ensure the secure creation of the account.
-
Login and JWT Authentication
- Users authenticate by entering their credentials (username and password).
- The system uses JWT (JSON Web Tokens) for secure session management. Tokens are signed with a secret key, ensuring their authenticity and integrity.
-
Role-Based Authorization
- The system dynamically assigns roles such as admin, user, or others to users.
- Permissions are granted based on the user’s role, allowing fine-grained control over who can access which resources.
-
Route Protection
- Specific routes are protected based on the authentication state and the roles assigned to the user.
guards
are employed to validate whether a user has access to certain routes or not.
-
Password Change and Recovery
- Users can request a password reset via email, ensuring they can regain access if they forget their credentials.
- Tokens are used for password resets, and they expire after a certain period for enhanced security.
-
Logout and Token Refresh
- A simple logout process invalidates the JWT, terminating the user’s session.
- Refresh tokens are implemented to allow users to stay logged in without needing to enter their credentials again.
-
Audit and Logging
- Important user activities, such as logins, failed login attempts, and password changes, are logged for audit purposes.
- This ensures that any suspicious activity can be monitored and addressed quickly.
-
Dynamic Role and Permission Management
- Roles can be created, updated, and dynamically assigned at runtime, providing flexibility in user management.
- Permissions can be customized for each role based on the application’s needs.
-
OAuth2 / Social Login Support
- The system supports OAuth2, allowing users to authenticate using third-party providers like Google, Facebook, and GitHub.
- This feature simplifies user login and eliminates the need to manually create accounts.
-
Multifactor Authentication (MFA)
- As an extra layer of security, MFA can be enabled. This requires users to provide a second form of verification, such as a code sent to their mobile device.
Prerequisites
Before starting with the installation, ensure you have the following prerequisites:
- Node.js: Make sure Node.js is installed.
- NestJS CLI: You will need the NestJS CLI to manage the project.
- Database: This system supports various databases such as PostgreSQL, MySQL, and MongoDB.
- OAuth2 Setup: You will also need OAuth2 credentials to integrate social logins.
Installation Guide
-
Clone the Repository:
git clone https://github.com/angelchavez19/nest-auth-template.git cd nest-auth-template
-
Install Dependencies: Install the required packages using npm:
npm install
-
Configure Environment Variables: Create a
.env
file and set up the database connection:DATABASE_URL="mysql://root:mysql@localhost:3306/nextauthdb" JWT_SECRET_KEY=<your-secret-key> CLIENT_DOMAIN=localhost CLIENT_URL=http://localhost:3000 SERVER_DOMAIN=localhost SERVER_URL=http://localhost:8000 # Email EMAIL_HOST=<your-email-host> EMAIL_PORT=<your-email-port> EMAIL_HOST_USER=<your-email-host-user> EMAIL_HOST_PASSWORD=<your-email-host-password>
-
Run the Development Server: Start the development server with the following command:
npm run start:dev
Technologies Used
- NestJS: A powerful and extensible Node.js framework for building efficient and scalable server-side applications.
- JSON Web Tokens (JWT): For secure, stateless user authentication.
- OAuth2: To enable third-party social login integrations.
- Prisma: For database schema management and querying.
- Bcrypt: For securely hashing user passwords.
Contact
If you have any questions or comments, feel free to contact the project maintainer:
- Email: infoangelchavez@gmail.com
- GitHub: angelchavez19
- LinkedIn: Angel Chávez
This authentication and authorization system is designed to make user management easier and more secure, offering advanced features like OAuth2 and multifactor authentication. By following the steps outlined above, you can easily implement this system in your own applications, ensuring your users are protected and their data is secure.