DEV Community

Mukarram Abdul karim
Mukarram Abdul karim

Posted on

Authentication and Authorization with NestJS, JWT, Guards Nestjs-modules/mailer, Dto, and TypeORM

  1. Setting up NestJS: • Install NestJS globally: npm install -g @nestjs/cli • Create a new NestJS project: nest new your-project-name • Navigate to the project directory: cd your-project-name
  2. Install Dependencies: • Install required packages: npm install @nestjs/jwt @nestjs-modules/mailer class-validator sendgrid @nestjs/typeorm typeorm, @bcrypt
  3. Configure TypeORM: • Set up your TypeORM configuration in app.module.js • 4. User Entity: • Create a User entity with necessary fields like email, password, password hashing etc., using TypeORM decorators. • BeforeInsert its replace the password with hashed characters using bcryptjs
  4. User Module: • Create an authentication module using nest generate module user. • Inside the module, create a service (UserService) for handling authentication logic.
  5. JWT Service: • Create a JwtModule to handle JWT configuration. Define a secret key and expiration time.
  6. User Controller: • Create an authentication controller (UserController) with routes for login, registration, and password reset link and forgot password route.
  7. Guards: • Implement a JWT guard using to validate JWT, Refresh token,logout token,reset password token, in requests. This guard will extract the token from the request and verify its validity.
  8. Authorization: • Implement authorization using guards. Define roles and permissions for different routes. Use guards to check if the user has the necessary roles or permissions to continue.
  9. Email Service: • Set up an email service using Nestjs-modules/mailer to send verification and new password to the emails. Inject this service into your user service.
  10. Registration Flow: • When a user registers, hash their password and create a verification token sent to the user email using the Nestjs-modules/mailer.
  11. Login Flow: • When a user logs in, validate their credentials, generate a JWT token, and return it in the response.
  12. Password Reset Flow: • Implement a password reset mechanism. When a user requests a password reset, generate a token, send a reset link to the user email, and allow the user to access their password.
  13. Protect Routes: • Use guards to protect routes that require authentication. Attach the guard to the route handler to ensure only authenticated users can access it i.e refresh token, log out token, reset password token, in this route.
  14. Error Handling:
    • Implement robust error handling throughout your authentication and authorization logic to provide meaningful feedback to users using (DTO).

  15. DTO:
    Implement robust error handling throughout your authentication and authorization

Top comments (0)