पाठ 11 / 34
Guards और Authentication
CanActivate guards, @UseGuards और Passport-आधारित JWT authentication से routes सुरक्षित करें।
Guard बनाएँ
एक guard एक class है जो CanActivate को implement करती है। Allow करने के लिए true return करें, reject करने के लिए false।
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
@Injectable()
export class JwtGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const token = request.headers.authorization?.split(' ')[1];
if (!token) return false;
try {
// verify token
return true;
} catch {
return false;
}
}
}Guard लागू करें
Routes या controllers पर @UseGuards() decorator उपयोग करें।
@UseGuards(JwtGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
// or on the controller
@Controller('admin')
@UseGuards(JwtGuard)
export class AdminController { ... }Passport.js integration
NestJS @nestjs/passport के साथ आता है seamless authentication के लिए—JWT, OAuth, local, आदि।