CORS: ai được gọi API của bạn?
CORS (Cross-Origin Resource Sharing) là cơ chế trình duyệt kiểm soát: “frontend ở domain A có được gọi API ở domain B không?”. Mặc định: KHÔNG. Bạn phải cấu hình server cho phép.
// File: cors.js
import cors from 'cors'
// ❌ SAI: cho phép tất cả — chỉ dùng khi dev
app.use(cors()) // origin: '*'
// ✅ ĐÚNG: chỉ cho phép domain frontend của bạn
app.use(cors({
origin: ['https://myapp.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true, // cho phép gửi cookie
}))
Helmet: thêm security headers tự động
Helmet là middleware Express thêm hàng loạt HTTP header bảo mật. Một dòng app.use(helmet()) bảo vệ chống nhiều loại tấn công phổ biến.
| Header | Chống gì | Helmet tự thêm? |
|---|---|---|
X-Content-Type-Options | Sniffing: trình duyệt tự đoán MIME type sai | ✅ |
X-Frame-Options | Clickjacking: nhúng trang bạn vào iframe | ✅ |
Strict-Transport-Security | Ép dùng HTTPS | ✅ |
Content-Security-Policy | XSS: chặn script lạ | ⚠️ Cần cấu hình thêm |
X-XSS-Protection | Bộ lọc XSS cũ của trình duyệt | ✅ |
// File: helmet.js
import helmet from 'helmet'
// Thêm toàn bộ security headers mặc định
app.use(helmet())
// Tuỳ chỉnh CSP nếu cần
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'cdn.jsdelivr.net'],
styleSrc: ["'self'", "'unsafe-inline'", 'fonts.googleapis.com'],
},
}))
Rate limiting: chống bot quét API
// File: ratelimit.js
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 phút
max: 100, // tối đa 100 request mỗi IP
message: { error: 'Quá nhiều request, thử lại sau 15 phút' },
})
// Áp cho toàn app
app.use(limiter)
// Hoặc chỉ cho route nhạy cảm
app.use('/api/auth', rateLimit({ windowMs: 60000, max: 5 }))
❓ CORS chặn request từ domain khác ở đâu?
- Cấu hình CORS với whitelist domain cụ thể
- Dùng Helmet để thêm security headers
- Thiết lập rate limiting cho route nhạy cảm
- Hiểu CORS là cơ chế trình duyệt, không phải server