Security · Backend

Bảo Mật API: 8 Kỹ Thuật Chống Tấn Công Từ Cơ Bản Đến Nâng Cao

Bảo Mật API - 8 kỹ thuật chống tấn công

Năm 2024, API attacks tăng 681% (Salt Security). APIs trở thành attack surface lớn nhất: chúng expose business logic, handle sensitive data (PII, payment info), và thường được viết vội vã để kịp deadline. OWASP API Security Top 10 (2023) liệt kê những lỗ hổng phổ biến nhất — và hầu hết preventable nếu implement đúng. Imperva 2024 report: 46% data breaches liên quan đến API vulnerabilities. Bài viết này chia sẻ 8 kỹ thuật bảo mật mà BanhCuonFlow áp dụng cho 200+ endpoints.

OWASP API Top 10: Hiểu Threats Trước

API1: Broken Object Level Authorization (BOLA) — lỗ hổng phổ biến nhất. User A đổi ID trong URL (/api/orders/123/api/orders/456) truy cập data user B. Fix: validate object ownership ở mọi endpoint. API2: Broken Authentication — weak tokens, no expiry, no MFA. API3: Broken Object Property Level Authorization — update fields không được phép (mass assignment: gửi {"role": "admin"} trong body). API4: Unrestricted Resource Consumption — no rate limiting, attacker gửi 1 triệu requests/phút → DDoS via API. API5: Broken Function Level Authorization — user thường gọi admin endpoints (/api/admin/users) vì backend không check role.

8 Kỹ Thuật Bảo Mật

① Authentication: JWT + Refresh Token

Mọi request cần Bearer Token (JWT). Access token expire 15 phút (short-lived giảm window of exploitation), refresh token 7 ngày (stored securely, httpOnly cookie). Khi access token expire → frontend dùng refresh token lấy access mới (silent refresh, no login lại). BanhCuonFlow: JWT chứa userId, departmentId, permissions — không chứa sensitive data (password, email). Signing key rotate quarterly. Algorithm: RS256 (asymmetric) cho production.

② Authorization: RBAC + Row-Level Security

Permission check ở 2 tầng: Function level — user có quyền gọi endpoint này? (RBAC middleware check role/permission trước khi vào controller). Data level — user có quyền thấy record này? (Row-level security: query tự filter theo departmentId/userId). Ví dụ: Manager phòng A chỉ thấy tasks phòng A, không thấy phòng B dù gọi cùng endpoint. BanhCuonFlow: permission matrix + department-based data isolation + organization hierarchy.

③ Input Validation

Validate TẤT CẢ input — never trust client. Type validation: số phải là số, email phải đúng format. Length limits: string max 1000 chars, page size max 100. Whitelist validation: status chỉ accept enum values (Active, Inactive), không accept arbitrary string. Range: amount > 0 và < MAX_INT. BanhCuonFlow: FluentValidation — mỗi DTO có validator riêng, validation errors trả về structured response.

④ SQL Injection Prevention

KHÔNG BAO GIỜ nối string thành SQL query: "SELECT * FROM users WHERE name = '" + input + "'" = invitation for SQL injection. Dùng parameterized queries hoặc ORM. BanhCuonFlow: 100% EF Core LINQ queries, zero raw SQL concatenation. Khi cần raw SQL → FromSqlInterpolated với parameterized placeholders. Bonus: enable EF Core query logging ở dev để spot any potential issues.

⑤ Rate Limiting

Chặn abuse và brute force: 100 requests/phút/user cho general API, 5 requests/phút cho login (brute force protection), 10 requests/giờ cho password reset, 1000 requests/phút cho public endpoints. .NET 7+ có built-in rate limiting middleware (fixed window, sliding window, token bucket, concurrency). BanhCuonFlow: sliding window rate limiter + IP-based + user-based + endpoint-specific limits. Response: 429 Too Many Requests với Retry-After header.

⑥ CORS Configuration

Chỉ allow requests từ trusted origins. KHÔNG dùng Access-Control-Allow-Origin: * trong production — đây là mời attacker vào nhà. BanhCuonFlow: whitelist specific domains (app.banhcuonflow.com), restrict methods (GET, POST, PUT, DELETE — không allow TRACE, OPTIONS wildcards), restrict headers, no credentials allowed from unknown origins.

⑦ HTTPS + Security Headers

100% HTTPS — redirect HTTP → HTTPS (HSTS preload). Security headers: Strict-Transport-Security: max-age=31536000; includeSubDomains, X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Content-Security-Policy (prevent XSS), Referrer-Policy: strict-origin-when-cross-origin. BanhCuonFlow: tất cả headers config qua Nginx reverse proxy + Helmet middleware.

⑧ Logging & Monitoring

Log mọi security event: failed logins (who, when, from where), permission denied attempts, validation errors, suspicious patterns (sequential ID scanning, rapid enumeration). Alert thresholds: >10 failed logins/user/phút → possible brute force, >100 4xx errors/phút → possible scanning, >10 BOLA attempts/user → possible data enumeration. BanhCuonFlow: structured JSON logs + audit trail ghi mọi CRUD action + correlation IDs cho distributed tracing.

Security-First Architecture

BanhCuonFlow: 8 security layers built-in. JWT, RBAC, rate limiting, audit logs — production-ready security không cần config thêm.