บทที่ 16: Security Best Practices
“บ้านที่แข็งแรงยังต้องมีระบบอลาร์มและกล้องวงจรปิด”
The Blueprint (พิมพ์เขียว)
Section titled “The Blueprint (พิมพ์เขียว)”แม้จะมี Authentication แล้ว ยังมีภัยคุกคามอีกมาก:
- Hackers พยายามเจาะระบบ
- Bots พยายาม Spam
- ช่องโหว่ ในโค้ดของเรา
Security = ระบบป้องกันขโมย
The Construction Site (หน้างานก่อสร้าง)
Section titled “The Construction Site (หน้างานก่อสร้าง)”🛡️ ภัยคุกคามหลัก (OWASP Top 10)
Section titled “🛡️ ภัยคุกคามหลัก (OWASP Top 10)”| ภัยคุกคาม | อันตราย | ป้องกัน |
|---|---|---|
| SQL Injection | แฮก Database | Parameterized Query |
| XSS | ขโมย Cookie | Sanitize HTML |
| CSRF | หลอกให้ทำ action | CSRF Token |
💉 SQL Injection
Section titled “💉 SQL Injection”// ❌ อันตราย!const query = `SELECT * FROM users WHERE id = ${userId}`;
// ✅ ใช้ Parameterized Queryconst query = `SELECT * FROM users WHERE id = $1`;await db.query(query, [userId]);🖥️ XSS (Cross-Site Scripting)
Section titled “🖥️ XSS (Cross-Site Scripting)”// ❌ อันตราย!<div dangerouslySetInnerHTML={{ __html: userInput }} />
// ✅ Sanitize HTMLimport DOMPurify from 'dompurify';<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />Material Selection (เลือกสเปกวัสดุ)
Section titled “Material Selection (เลือกสเปกวัสดุ)”🚦 Rate Limiting
Section titled “🚦 Rate Limiting”import rateLimit from 'express-rate-limit';
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 นาที max: 100, // สูงสุด 100 requests});
app.use('/api/', limiter);✅ Input Validation (Zod)
Section titled “✅ Input Validation (Zod)”import { z } from 'zod';
const UserSchema = z.object({ email: z.string().email('อีเมลไม่ถูกต้อง'), password: z.string() .min(8, 'ต้องมีอย่างน้อย 8 ตัว') .regex(/[A-Z]/, 'ต้องมีตัวพิมพ์ใหญ่'),});🔑 Security Headers (Helmet)
Section titled “🔑 Security Headers (Helmet)”import helmet from 'helmet';app.use(helmet());Architect’s Note (บันทึกสถาปนิก)
Section titled “Architect’s Note (บันทึกสถาปนิก)”⚠️ Checklist ความปลอดภัย
Section titled “⚠️ Checklist ความปลอดภัย”- ✅ HTTPS everywhere
- ✅ Input validation ทุก endpoint
- ✅ Parameterized queries
- ✅ CSRF protection
- ✅ Rate limiting
- ✅ Security headers
💡 Best Practices
Section titled “💡 Best Practices”- Principle of Least Privilege — ให้สิทธิ์เท่าที่จำเป็น
- Defense in Depth — หลายชั้นความปลอดภัย
- Keep Dependencies Updated —
npm audit