Table of Contents
Implementing secure authentication is crucial for protecting your application and user data. NestJS, a progressive Node.js framework, combined with Passport.js, a popular authentication middleware, provides a robust solution for handling authentication securely. This guide walks you through setting up secure authentication in NestJS using Passport.js.
Prerequisites
- Node.js installed on your system
- Basic knowledge of NestJS framework
- Understanding of Passport.js concepts
- An existing NestJS project
Step 1: Install Necessary Packages
- Install Passport.js and its NestJS integration:
npm install @nestjs/passport passport passport-local @types/passport-local
Step 2: Configure Passport Module
Import and configure the PassportModule in your main module or a dedicated auth module.
In auth.module.ts:
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { LocalStrategy } from './local.strategy';
@Module({
imports: [PassportModule],
providers: [LocalStrategy],
})
Step 3: Create the Local Strategy
Define the local authentication strategy by extending Passport’s LocalStrategy.
In local.strategy.ts:
import { Strategy } from 'passport-local';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { UsersService } from '../users/users.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private usersService: UsersService) {
super();
}
async validate(username: string, password: string): Promise
const user = await this.usersService.findOne(username);
if (user && user.password === password) {
return user;
}
throw new UnauthorizedException();
}
}
Step 4: Create Authentication Controller
Handle login requests and generate JWT tokens or sessions.
In auth.controller.ts:
import { Controller, Post, Request, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
@UseGuards(AuthGuard('local'))
@Post('login')
async login(@Request() req) {
// Generate token or session here
return { message: 'Login successful', user: req.user };
}
}
Step 5: Protect Routes
Use guards to protect routes that require authentication.
In any controller:
import { UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@UseGuards(AuthGuard('local'))
@Get('protected')
async getProtectedResource() {
return { message: 'This is a protected resource' };
}
Summary
Setting up secure authentication in NestJS with Passport.js involves installing the right packages, configuring the Passport module, creating strategies, handling login requests, and protecting routes. By following these steps, you can ensure your application handles user authentication securely and efficiently.