Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 12: Guard trong NestJS

Tiếp tục với series, ở bài trước chúng ta đã ghi log mọi request, nhưng ai gọi đến TaskFlow API cũng xem, sửa, xoá được project. Bài này mình sẽ giới thiệu với mọi người về guard trong NestJS và viết một guard API key tạm để khoá API lại.

1. Guard là gì?

Guard là class có @Injectable(), cài đặt interface CanActivate, có nhiệm vụ duy nhất là quyết định request có được đi tiếp vào route handler hay không.

Trong Express, việc này hay viết bằng middleware, nhưng middleware không biết route handler nào sẽ chạy sau next(). Guard nhận được ExecutionContext nên biết chính xác handler sắp chạy và đọc được các "nhãn" gắn trên route như @Public(), @Roles() ở phần 4, 5.

Guard chạy sau tất cả middleware và trước pipe (thứ tự đầy đủ mình sẽ nói ở Bài 13). Method canActivate() trả về true thì request được xử lý, false thì NestJS từ chối với lỗi 403.

2. Tạo guard API key.

Chưa có đăng nhập, mình bảo vệ TaskFlow API bằng một API key gửi trong header X-API-Key. Các bạn tạo guard bằng Nest CLI rồi sửa lại nội dung:

nest g guard common/guards/api-key --no-spec --flat --format
# CREATE src/common/guards/api-key.guard.ts (315 bytes)

- src/common/guards/api-key.guard.ts

import { createHash, timingSafeEqual } from 'node:crypto';
import {
    CanActivate,
    ExecutionContext,
    Injectable,
    UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';

// Băm SHA-256 để hai buffer đem so sánh luôn dài bằng nhau (32 byte)
function sha256(value: string): Buffer {
    return createHash('sha256').update(value).digest();
}

@Injectable()
export class ApiKeyGuard implements CanActivate {
    canActivate(context: ExecutionContext): boolean {
        const request = context.switchToHttp().getRequest<Request>();
        const apiKey = request.header('x-api-key');
        const expected = process.env.API_KEY;

        if (
            !expected ||
            !apiKey ||
            !timingSafeEqual(sha256(apiKey), sha256(expected))
        ) {
            throw new UnauthorizedException('API key không hợp lệ');
        }
        return true;
    }
}

Trong đó:

  • context.switchToHttp().getRequest(): lấy Request của Express, giống ArgumentsHost trong filter ở Bài 10 (ExecutionContext kế thừa ArgumentsHost).
  • process.env.API_KEY: key đọc từ biến môi trường, không viết cứng trong code (Bài 14 chuyển sang ConfigService). Chưa đặt API_KEY thì mọi request đều bị từ chối.
  • timingSafeEqual(): so sánh mất cùng một thời gian dù sai ở ký tự nào, nên không thể đo thời gian phản hồi để đoán dần key như với === (hàm cần hai buffer dài bằng nhau nên mình so sánh mã SHA-256).
  • Ném UnauthorizedException để trả 401 thay vì return false (luôn là 403). Lỗi này đi qua AllExceptionsFilter nên vẫn đúng định dạng chung.

Lưu ý: Đây chỉ là cách bảo vệ tạm thời (cả ứng dụng dùng chung một key), Bài 20 sẽ thay bằng guard JWT cho từng user.

3. Áp dụng guard.

Giống pipe và filter, guard gắn được ở cấp method, controller hoặc toàn cục. Ở cấp controller, các bạn dùng @UseGuards() với class guard (NestJS tự khởi tạo và inject dependency):

- src/projects/projects.controller.ts (đoạn trích, thêm UseGuards vào import từ @nestjs/common)

import { ApiKeyGuard } from '../common/guards/api-key.guard.js';

@Controller('projects')
@UseGuards(ApiKeyGuard)
export class ProjectsController {
    // ...
}

Đặt trên một method thì chỉ route đó cần key. Giờ tạo một key ngẫu nhiên và truyền qua biến môi trường khi khởi động:

node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
# c94cb41b45df9a5066381edd89563d493a0eff856ffde9a957f752abe1dd7f69 (mỗi lần chạy ra key khác)

API_KEY=<key vừa tạo> npm run start:dev
curl http://localhost:3000/api/v1/projects/1
# {"statusCode":401,"errorCode":"UNAUTHORIZED","message":"API key không hợp lệ","path":"/api/v1/projects/1","timestamp":"2026-11-15T06:55:35.174Z"}

curl http://localhost:3000/api/v1/projects/1 -H 'X-API-Key: <key vừa tạo>'
# {"id":1,"name":"Website toidicode.com","description":"Viết lại giao diện","ownerId":1}

4. Metadata, custom decorator @Public và guard toàn cục.

Mình muốn mọi route đều cần key (quên gắn guard cũng không bị lộ), trừ route công khai như GET /api/v1: đăng ký guard toàn cục và đánh dấu route công khai bằng metadata: dữ liệu decorator gắn lên handler hoặc controller, guard đọc lại lúc chạy.

Các bạn tạo custom decorator @Public() bằng SetMetadata():

- src/common/decorators/public.decorator.ts

import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';

// Đánh dấu route không cần API key
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

Guard inject Reflector để đọc metadata. getHandler() của ExecutionContext trả về method sắp chạy, getClass() trả về class controller, getAllAndOverride() lấy giá trị đầu tiên tìm thấy theo thứ tự đó:

- src/common/guards/api-key.guard.ts (đoạn trích, thêm hai import)

import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator.js';

@Injectable()
export class ApiKeyGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) {}

    canActivate(context: ExecutionContext): boolean {
        const isPublic = this.reflector.getAllAndOverride<boolean>(
            IS_PUBLIC_KEY,
            [context.getHandler(), context.getClass()],
        );
        if (isPublic) {
            return true;
        }

        // ... phần kiểm tra API key giữ nguyên như phần 2
    }
}

Guard cần DI nên không dùng được app.useGlobalGuards() trong main.ts (nằm ngoài mọi module). Các bạn xoá @UseGuards(ApiKeyGuard) cùng các import của nó ở ProjectsController, rồi đăng ký trong AppModule với token APP_GUARD:

- src/app.module.ts (đoạn trích)

import { APP_GUARD } from '@nestjs/core';
import { ApiKeyGuard } from './common/guards/api-key.guard.js';

@Module({
    imports: [ProjectsModule, TasksModule],
    controllers: [AppController],
    providers: [AppService, { provide: APP_GUARD, useClass: ApiKeyGuard }],
})

Cuối cùng gắn @Public() lên route chào mừng:

- src/app.controller.ts (đoạn trích, import Public từ ./common/decorators/public.decorator.js)

@Public()
@Get()
getHello(): string {
    return this.appService.getHello();
}
curl http://localhost:3000/api/v1
# Xin chào TaskFlow API!

curl http://localhost:3000/api/v1/projects
# {"statusCode":401,"errorCode":"UNAUTHORIZED","message":"API key không hợp lệ","path":"/api/v1/projects","timestamp":"2026-11-15T06:56:58.382Z"}

DELETE /api/v1/projects/abc không có key cũng nhận 401 chứ không phải 400 của ParseIdPipe, vì guard chạy trước pipe. Route không tồn tại vẫn trả 404 vì không có handler để guard kiểm tra.

5. Custom decorator @Roles với Reflector.createDecorator.

Reflector.createDecorator() tạo decorator có kiểu rõ ràng mà không cần tự đặt key. VD: @Roles() nhận danh sách role được phép, guard kiểm tra role của user:

- src/common/decorators/roles.decorator.ts

import { Reflector } from '@nestjs/core';

export const Roles = Reflector.createDecorator<string[]>();

- src/common/guards/roles.guard.ts

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { Roles } from '../decorators/roles.decorator.js';

@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private readonly reflector: Reflector) {}

    canActivate(context: ExecutionContext): boolean {
        const roles = this.reflector.getAllAndOverride(Roles, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (!roles) {
            return true; // route không yêu cầu role
        }

        const request = context
            .switchToHttp()
            .getRequest<Request & { user?: { roles: string[] } }>();
        const userRoles = request.user?.roles ?? [];
        return roles.some((role) => userRoles.includes(role));
    }
}

Truyền Roles vào getAllAndOverride() thì TypeScript tự biết roles là string[]. Thử gắn lên route xoá project (thêm các import tương ứng):

@Delete(':id')
@Roles(['admin'])
@UseGuards(RolesGuard)
@HttpCode(204)
remove(@Param('id', ParseIdPipe) id: number): void {
    this.projectsService.remove(id);
}
curl -X DELETE http://localhost:3000/api/v1/projects/1 -H 'X-API-Key: <key vừa tạo>'
# {"statusCode":403,"errorCode":"FORBIDDEN","message":"Forbidden resource","path":"/api/v1/projects/1","timestamp":"2026-11-15T06:57:29.983Z"}

Guard toàn cục chạy trước guard của method nên thiếu key vẫn là 401. Có key thì RolesGuard trả false (chưa có request.user) và NestJS trả 403. Bài 20 gắn user vào request, Bài 21 hoàn thiện phân quyền, giờ các bạn xoá đoạn thử này và hai file vừa tạo.

6. Lời kết.

Như vậy mình đã giới thiệu với mọi người về guard trong NestJS: CanActivate, ExecutionContext, guard ở cấp route, controller, toàn cục, metadata với Reflector qua @Public, @Roles, và guard API key tạm cho TaskFlow API. Bài sau mình sẽ giới thiệu về interceptor trong NestJS, chạy code cả trước lẫn sau route handler, và dùng nó bọc mọi response thành dạng { data }.

Đă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!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha