NestJSAdvanced
NestJS Authentication (JWT)
JWT install, register/login, passport/guard, bcrypt — NestJS auth বাংলায়।
14টি অংশবাংলা ভাষায়
NestJS-এ JWT authentication অফিসিয়াল @nestjs/jwt ও Passport দিয়ে করা হয়। সম্পূর্ণ flow এখানে।
Setup
npm i @nestjs/jwt bcryptjs
npm i -D @types/bcryptjs.envenv
env
JWT_SECRET=your_super_secret
JWT_EXPIRES=3600,Auth Service
src/auth/auth.service.tstypescript
typescript
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import * as bcrypt from "bcryptjs";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService,
) {}
async register(dto: any) {
const hashed = await bcrypt.hash(dto.password, 10);
const user = await this.usersService.create({
...dto,
password: hashed,
});
return user;
}
async login(email: string, password: string) {
const user = await this.usersService.findByEmail(email);
if (!user) throw new UnauthorizedException("Email বা password ভুল");
const ok = await bcrypt.compare(password, user.password);
if (!ok) throw new UnauthorizedException("Email বা password ভুল");
const payload = { sub: user._id, email: user.email, role: user.role };
return {
access_token: await this.jwtService.signAsync(payload),
user: { id: user._id, email: user.email },
};
}
}Auth Module & JwtModule
src/auth/auth.module.tstypescript
typescript
import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt";
import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
@Module({
imports: [
UsersModule,
JwtModule.registerAsync({
global: true,
useFactory: () => ({
secret: process.env.JWT_SECRET,
signOptions: {
expiresIn: process.env.JWT_EXPIRES,
},
}),
}),
],
controllers: [AuthController],
providers: [AuthService],
})
export class AuthModule {}Auth Controller
src/auth/auth.controller.tstypescript
typescript
import { Body, Controller, Post, HttpCode } from "@nestjs/common";
import { AuthService } from "./auth.service";
@Controller("auth")
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post("register")
register(@Body() dto: any) {
return this.authService.register(dto);
}
@Post("login")
@HttpCode(200)
login(@Body() dto: { email: string; password: string }) {
return this.authService.login(dto.email, dto.password);
}
}Guards-এ JWT verify
src/common/jwt-auth.guard.tstypescript
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const [type, token] = request.headers.authorization?.split(" ") ?? [];
if (type !== "Bearer" || !token) {
throw new UnauthorizedException();
}
try {
request["user"] = await this.jwtService.verifyAsync(token);
} catch {
throw new UnauthorizedException();
}
return true;
}
}
// ব্যবহার
@Get("me")
@UseGuards(JwtAuthGuard)
getMe(@Req() req) {
return req["user"];
}# test flow
POST /auth/register { name, email, password }
POST /auth/login { email, password } → access_token
GET /users/me
Authorization: Bearer <access_token>Production সতর্কতা
JWT_SECRET শক্তিশালী ও environment-এ রাখুন। refresh token ও logout-এর জন্য @nestjs/jwt refresh strategy গবেষণা করুন।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।