Guards trong NestJS

Guards là một công cụ để xác định liệu một request có nên được xử lý bởi route handler hay không. Chúng chủ yếu được sử dụng cho authenticationauthorization. Một guard là một class implement interface CanActivate với một method canActivate().

Khái Niệm Guard

Guard có một trách nhiệm duy nhất: xác định liệu một request có được phép truy cập resource hay không. Guard được thực thi sau middleware nhưng trước pipes.

Request Processing Pipeline (with Guards)

ExecutionContext

ExecutionContext cung cấp thông tin chi tiết về request hiện tại:

Built-in Guards

NestJS cung cấp một số built-in guards thông qua @nestjs/passport:

Cơ Bản về Guards

1. Simple Authentication Guard

2. Roles Guard

Ví Dụ Guards Thực Tế

1. JWT Authentication Guard

2. Optional JWT Guard

3. API Key Guard

4. Owner Guard (Resource Ownership)

5. Time-based Guard

6. IP Whitelist Guard

7. Permission-based Guard

8. Rate Limiting Guard

9. Custom Metadata Guard

Guards at Different Scopes

Method-level

Class-level

Global-level

Module-level (Provider)

Async Guards

Guards có thể async:

Guards vs Other Features

Best Practices

1. Tách Biệt Concerns

2. Reusable Guards

3. Proper Error Handling

4. Use Reflector cho Metadata

5. Guard Order Matters

Complete Example

Kết Luận

Guards là công cụ quan trọng để:
  • Xác thực users (authentication)
  • Kiểm tra quyền (authorization)
  • Kiểm soát truy cập (access control)
  • Bảo vệ resources khỏi truy cập không được phép
Sử dụng Guards đúng cách giúp bạn:
  • Xây dựng ứng dụng secure
  • Kiểm soát quyền truy cập một cách tập trung
  • Tái sử dụng logic authentication/authorization
  • Giảm boilerplate code
  • Tạo ứng dụng maintainable và scalable