Tiếp tục với series, ở Bài 12 TaskFlow API chỉ khoá bằng một API key dùng chung. Bài này mình sẽ giới thiệu với mọi người về xác thực với JWT trong NestJS để mỗi user có tài khoản và token riêng.
1. JWT là gì?
JWT (JSON Web Token) là chuỗi header.payload.signature. Payload chứa các claim như sub (id user), exp (hết hạn); signature ký bằng secret của server nên sửa payload là token hỏng. Token không mã hoá, đừng đặt dữ liệu nhạy cảm vào. Client đăng nhập, nhận access token rồi gửi header Authorization: Bearer <token>. Server không lưu token nên không thu hồi được, vì vậy token nên sống ngắn (15 phút).
Tài liệu NestJS giới thiệu package mới @nestjs/authentication (mới bản 0.1.6). Mình dùng @nestjs/jwt 12.0.5 với guard tự viết để các bạn hiểu cơ chế (argon2 0.45.2, @nestjs/throttler 6.7.1):
npm install @nestjs/jwt @nestjs/throttler argon2
2. Lưu mật khẩu đã băm.
Không bao giờ lưu mật khẩu gốc, chỉ lưu mã băm một chiều. Mình dùng argon2 (argon2id, tốn RAM nên dò bằng GPU rất chậm); bcrypt chỉ đọc 72 byte đầu của mật khẩu.
Model User thêm cột password String. Bảng users đã có dữ liệu nên không thêm được cột bắt buộc: tạo migration rồi reset như Bài 16. Trước đó, user trong prisma/seed.ts thêm password: await hash('matkhau123') (import { hash } from 'argon2').
npx prisma migrate dev --name user_password --create-only
npx prisma migrate reset --force
npx prisma generate
npx prisma db seed
Như Bài 14, envSchema thay API_KEY bằng JWT_SECRET (z.string().min(32)), JWT_EXPIRES_IN (giây, mặc định 900), auth.config.ts trả về jwtSecret, jwtExpiresIn; sửa .env, .env.example theo.
3. Đăng ký và đăng nhập.
Tạo module, service, controller auth bằng Nest CLI. RegisterDto có name, email (@IsEmail()), password (@MinLength(8) @MaxLength(128)); LoginDto có email, password. src/auth/auth-user.ts export AUTH_USER_SELECT ({ id, name, email }, không có password), kiểu AuthUser và AuthRequest = Request & { user?: AuthUser }.
- src/auth/auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { hash, verify } from 'argon2';
import { PrismaService } from '../prisma/prisma.service.js';
import { AUTH_USER_SELECT, type AuthUser } from './auth-user.js';
import type { LoginDto } from './dto/login.dto.js';
import type { RegisterDto } from './dto/register.dto.js';
// Mã băm giả: email không tồn tại cũng mất thời gian verify như thường
const DUMMY_HASH = await hash('mat-khau-gia');
@Injectable()
export class AuthService {
constructor(
private readonly prisma: PrismaService,
private readonly jwtService: JwtService,
) {}
async register(dto: RegisterDto): Promise<AuthUser> {
return this.prisma.user.create({
data: {
name: dto.name,
email: dto.email.toLowerCase(),
password: await hash(dto.password), // argon2id, salt ngẫu nhiên
},
select: AUTH_USER_SELECT,
});
}
async login(dto: LoginDto): Promise<{ accessToken: string }> {
const user = await this.prisma.user.findUnique({
where: { email: dto.email.toLowerCase() },
});
const valid = await verify(user?.password ?? DUMMY_HASH, dto.password);
if (!user || !valid) {
throw new UnauthorizedException('Email hoặc mật khẩu không đúng');
}
const accessToken = await this.jwtService.signAsync({
sub: String(user.id),
});
return { accessToken };
}
}
Trong đó:
hash()trả về$argon2id$v=19$m=65536,t=3,p=4$<salt>$<hash>chứa sẵn tham số và salt choverify().- Sai email hay mật khẩu đều cùng thông báo, cùng thời gian nên
loginkhông lộ email đã đăng ký. Nhưngregistervẫn trả 409 (PrismaExceptionFilter) khi trùng email: muốn kín phải xác minh email, ít nhất siết@Throttleriêng cho route này.
- src/auth/auth.module.ts (đoạn trích imports)
JwtModule.registerAsync({
inject: [authConfig.KEY],
useFactory: (auth: ConfigType<typeof authConfig>) => ({
secret: auth.jwtSecret,
signOptions: {
algorithm: 'HS256',
expiresIn: auth.jwtExpiresIn,
},
verifyOptions: { algorithms: ['HS256'] },
}),
}),
Ghim algorithms thì token ký bằng thuật toán khác (none, HS512) bị từ chối.
4. Guard JWT toàn cục và @Public.
Xoá ApiKeyGuard và dòng APP_GUARD của nó trong AppModule. Guard mới đăng ký trong providers của AuthModule ({ provide: APP_GUARD, useClass: JwtAuthGuard }) để inject được JwtService, bỏ qua route @Public():
- src/auth/jwt-auth.guard.ts
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { IS_PUBLIC_KEY } from '../common/decorators/public.decorator.js';
import { PrismaService } from '../prisma/prisma.service.js';
import { AUTH_USER_SELECT, type AuthRequest } from './auth-user.js';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly jwtService: JwtService,
private readonly prisma: PrismaService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(
IS_PUBLIC_KEY,
[context.getHandler(), context.getClass()],
);
if (isPublic) {
return true;
}
const request = context.switchToHttp().getRequest<AuthRequest>();
const [type, token] = request.headers.authorization?.split(' ') ?? [];
// Token sai hoặc hết hạn: verifyAsync ném lỗi -> null
const payload =
type === 'Bearer' && token
? await this.jwtService
.verifyAsync<{ sub: string }>(token)
.catch(() => null)
: null;
const user =
payload &&
(await this.prisma.user.findUnique({
where: { id: Number(payload.sub) },
select: AUTH_USER_SELECT,
}));
if (!user) {
throw new UnauthorizedException(); // 401 chung, không nói lý do
}
request.user = user;
return true;
}
}
Đọc lại user từ database tốn một query mỗi request, nhưng user bị xoá thì token cũ vô hiệu ngay.
5. Lấy user hiện tại với @CurrentUser.
Thay vì @Req() rồi đọc req.user, mình viết param decorator:
- src/auth/current-user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { AuthRequest, AuthUser } from './auth-user.js';
// @CurrentUser(): lấy user mà JwtAuthGuard đã gắn vào request
export const CurrentUser = createParamDecorator(
(_data: unknown, context: ExecutionContext): AuthUser | undefined =>
context.switchToHttp().getRequest<AuthRequest>().user,
);
- src/auth/auth.controller.ts (đoạn trích, register() viết giống login() nhưng không có @HttpCode, @Throttle)
@Public()
@Post('login')
@HttpCode(200)
@Throttle({ default: { limit: 5, ttl: minutes(1) } }) // 5 lần/phút mỗi IP
login(@Body() dto: LoginDto): Promise<{ accessToken: string }> {
return this.authService.login(dto);
}
@Get('me')
me(@CurrentUser() user: AuthUser): AuthUser {
return user;
}
ProjectsController.create() thêm @CurrentUser() user: AuthUser, truyền user.id làm ownerId thay số 1 viết cứng. Thử với dữ liệu vừa reset:
curl http://localhost:3000/api/v1/auth/register -H "Content-Type: application/json" \
-d '{"name":"Nguyen Van An","email":"[email protected]","password":"matkhau456"}'
# {"data":{"id":2,"name":"Nguyen Van An","email":"[email protected]"}}
curl http://localhost:3000/api/v1/auth/login -H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"matkhau456"}'
# {"data":{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}}
T='Authorization: Bearer <accessToken>'
curl http://localhost:3000/api/v1/auth/me -H "$T"
# {"data":{"id":2,"name":"Nguyen Van An","email":"[email protected]"}}
curl http://localhost:3000/api/v1/projects -H "$T" -H "Content-Type: application/json" -d '{"name":"Blog"}'
# {"data":{"id":3,"name":"Blog","description":"","ownerId":2,...}}
6. Giới hạn đăng nhập với @nestjs/throttler.
Để chống dò mật khẩu, @nestjs/throttler đếm request theo IP và route, vượt ngưỡng trả 429. Trong AppModule, thêm ThrottlerModule.forRoot([{ ttl: minutes(1), limit: 100 }]) vào imports (ttl tính bằng mili giây) và { provide: APP_GUARD, useClass: ThrottlerGuard } vào providers. Guard toàn cục của module gốc chạy trước guard của AuthModule, nên request mang token bừa cũng bị đếm.
@Throttle() ở phần 5 siết login còn 5 lần/phút: lần thứ 6, kể cả đúng mật khẩu, nhận 429 kèm header Retry-After: 60.
Lưu ý: Giới hạn chỉ tính theo IP, kẻ có nhiều IP vẫn dò được một tài khoản. Khi chạy thật nên thêm throttler đếm theo email + IP như tài liệu NestJS (chỉ theo email thì ai cũng khoá được tài khoản người khác), kèm mật khẩu mạnh hoặc 2FA.
Sau reverse proxy, mọi client chung IP của proxy: tạo app bằng NestFactory.create<NestExpressApplication>() rồi gọi app.set('trust proxy', 'loopback') (địa chỉ của proxy). Đừng đặt true hay bật khi không có proxy, client sẽ tự khai IP qua X-Forwarded-For để lách giới hạn.
7. Lời kết.
Như vậy mình đã giới thiệu với mọi người về xác thực với JWT trong NestJS: băm mật khẩu, đăng nhập, guard JWT, @CurrentUser(), throttler. Đăng ký là công khai nên hiện mọi tài khoản sửa, xoá được mọi project, task và cả nhật ký (DELETE /activities), đừng deploy ở bước này. Bài sau mình sẽ giới thiệu về phân quyền trong NestJS.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments