NashTech Blog

Mastering Authentication in Nest.js with Passport Local Strategy

Table of Contents
Mastering Authentication in Nest.js with Passport Local Strategy

Introduction

Authentication is a cornerstone of web application security, and Nest.js, with its modular and flexible architecture, makes implementing authentication a breeze. In this blog, we’ll explore how to authenticate users using the Passport Local Strategy in Nest.js, leveraging its simplicity and robustness to enhance the security of your applications.

Understanding Passport Local Strategy

Passport is a popular authentication middleware for Node.js that provides a simple, yet powerful, way to authenticate users. The Local Strategy, one of Passport’s many authentication strategies, is ideal for authenticating users based on a username and password stored in a database.

To understand about authentication in nest.js Click Here.

Setting Up the Environment

Before diving into code, ensure you have Nest.js installed along with Passport and the necessary dependencies. You can install them using npm:

npm install @nestjs/passport passport passport-local

Implementing Local Authentication

  1. User Entity: First, create a User entity to represent users in your application. Define properties such as username, password (hashed), email, etc. Ensure to hash passwords securely using libraries like bcrypt.

    // user.entity.ts
    import { Entity, Column, PrimaryGeneratedColumn } from ‘typeorm’;@Entity()
    export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({ unique: true })
    username: string;

    @Column()
    password: string; // Hashed password

    @Column()
    email: string;
    }

  2. Auth Module: Create an AuthModule to encapsulate authentication-related functionality. Define a PassportLocalModule to configure Passport with the Local Strategy.

    // auth.module.ts
    import { Module } from ‘@nestjs/common’;
    import { PassportModule } from ‘@nestjs/passport’;
    import { AuthService } from ‘./auth.service’;
    import { LocalStrategy } from ‘./local.strategy’;@Module({
    imports: [
    PassportModule,
    ],
    providers: [AuthService, LocalStrategy],
    exports: [AuthService], // Export AuthService for dependency injection
    })
    export class AuthModule {}

  1. Local Strategy: Implement the LocalStrategy class by extending PassportStrategy from @nestjs/passport. Override the validate() method to verify user credentials and return the user if authentication succeeds.

    // local.strategy.ts
    import { Injectable } from ‘@nestjs/common’;
    import { PassportStrategy } from ‘@nestjs/passport’;
    import { Strategy } from ‘passport-local’;
    import { AuthService } from ‘./auth.service’;@Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
     constructor(private authService: AuthService) {
      super();
     }

     async validate(username: string, password: string): Promise<any> {
      const user = await this.authService.validateUser(username, password);
      if (!user) {
       throw new UnauthorizedException();
      }
      return user;
      }
    }

  1. Auth Service: Create an AuthService to handle authentication logic. Inject necessary dependencies such as UserRepository for fetching user data. Implement methods like validateUser() to authenticate users based on provided credentials.

    // auth.service.ts
    import { Injectable } from ‘@nestjs/common’;
    import { JwtService } from ‘@nestjs/jwt’;
    import { User } from ‘./user.entity’;@Injectable()
    export class AuthService {
      constructor(private jwtService: JwtService) {}async validateUser(username: string, password: string): Promise<User |       null> {
    // Logic to validate user against database
    // Example: const user = await this.userService.findByUsername(username);
    // Ensure to validate password hash
    // Example: const isValidPassword = await bcrypt.compare(password, user.password);
    // Return user if valid, otherwise return null
    }

      async login(user: User) {
      const payload = { username: user.username, sub: user.id };
      return {
      access_token: this.jwtService.sign(payload),
      };
     }
    }

  1. Auth Controller: Develop an AuthController to expose authentication endpoints like /login. Inject the AuthService and use it to authenticate users. Upon successful authentication, generate and return a JWT token for subsequent requests.

    // auth.controller.ts
    import { Controller, Post, Request, UseGuards } from ‘@nestjs/common’;
    import { AuthGuard } from ‘@nestjs/passport’;
    import { AuthService } from ‘./auth.service’;@Controller(‘auth’)
    export class AuthController {
      constructor(private authService: AuthService) {}@UseGuards(AuthGuard(‘local’))
      @Post(‘login’)
      async login(@Request() req) {
      return this.authService.login(req.user);
      }
    }

Securing Endpoints

Once authentication is set up, secure your application endpoints using guards provided by @nestjs/passport. Apply guards like AuthGuard(‘local’) to routes that require authentication, ensuring only authenticated users can access them.

// app.module.ts
import { Module } from ‘@nestjs/common’;
import { AuthModule } from ‘./auth/auth.module’;
import { AppController } from ‘./app.controller’;
import { AppService } from ‘./app.service’;

@Module({
imports: [AuthModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

Conclusion

Implementing authentication in Nest.js using Passport Local Strategy empowers you to build secure and robust applications effortlessly. By leveraging Nest.js’ modular architecture and Passport’s simplicity, you can enhance the security of your applications while focusing on delivering exceptional user experiences. Start integrating authentication into your Nest.js projects today and elevate your application security to new heights.

Checkout the code here – GitHub

For more detail checkout the NestJS documentation.

With these thank you if you were there till the end. For more such blogs and updates follow Front-end Competency.

Follow NashTech Blogs for more amazing blogs.

Picture of Sandeep Gusain

Sandeep Gusain

I am Software Developer at NashTech and I possess extensive expertise in Node.js and MongoDB. Passionate about tackling challenges and constant learning, I aim to share my knowledge. Beyond coding, I enjoy playing football and trekking.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top