Bảo mật Web: OWASP Top 10 cho Node.js và React
Hướng dẫn bảo mật thực chiến — ngăn chặn SQL injection, XSS, broken authentication, IDOR và security misconfiguration.
Hầu hết các vụ breach đều khai thác lỗ hổng phổ biến, có thể phòng tránh được. Hướng dẫn này covers OWASP Top 10 với code Node.js thực tế.
1. SQL Injection
// LỖ HỔNG
const users = await db.query(`SELECT * FROM users WHERE email = '${email}'`);
// AN TOÀN — parameterized query
const users = await db.query("SELECT * FROM users WHERE email = $1", [email]);
// AN TOÀN — ORM
const user = await prisma.user.findUnique({ where: { email } });
2. Xác thực An toàn
import bcrypt from "bcryptjs";
async function hashPassword(password: string) {
return bcrypt.hash(password, 12); // 12 rounds tối thiểu
}
async function signToken(userId: string) {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
return new SignJWT({ sub: userId })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("15m") // Access token ngắn hạn
.sign(secret);
}
// Rate limiting — chống brute force
const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 });
app.post("/auth/login", loginLimiter, loginHandler);
3. XSS Prevention
// React tự động escape — an toàn mặc định
const Profile = ({ name }: { name: string }) => <h1>{name}</h1>;
// Sanitize rich text trước khi render
import DOMPurify from "isomorphic-dompurify";
const SafeContent = ({ html }: { html: string }) => (
<div
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(html, { ALLOWED_TAGS: ["p", "b", "i", "a"] }),
}}
/>
);
4. IDOR — Kiểm tra quyền sở hữu
// AN TOÀN — kiểm tra ownership
app.get("/orders/:id", authenticate, async (req, res) => {
const order = await db.orders.findFirst({
where: { id: req.params.id, userId: req.user.id },
});
if (!order) return res.status(404).json({ error: "Không tìm thấy" });
res.json(order);
});
5. Security Headers
import helmet from "helmet";
app.use(helmet({
contentSecurityPolicy: {
directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"] },
},
hsts: { maxAge: 31536000, includeSubDomains: true },
}));
Checklist Bảo mật
- Tất cả SQL query dùng parameterized statements
- Mật khẩu hash với bcrypt rounds >= 12
- JWT access token hết hạn trong < 1 giờ
- Rate limiting cho login (5 lần / 15 phút)
- Security headers qua Helmet
- Kiểm tra authorization trên mỗi endpoint
Kết luận
Bảo mật phải được tích hợp từ đầu. Ventra Rocket đưa security review vào quy trình delivery của mọi dự án.
Bài viết liên quan
Next.js App Router: Patterns cho Production
Hướng dẫn thực chiến xây dựng web app nhanh với Next.js App Router — server components, streaming, parallel routes, caching strategies.
10 TypeScript Pattern giúp code sạch hơn
Tổng hợp 10 TypeScript pattern thực tiễn — từ discriminated unions, template literal types đến satisfies operator — giúp code type-safe và dễ bảo trì.
Quản lý State trong React 2026: Zustand, TanStack Query và URL State
Chọn đúng công cụ quản lý state trong React — TanStack Query cho server state, Zustand cho global UI state, URL cho filter, useState cho local state.