Skip to content

บทที่ 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แฮก DatabaseParameterized Query
XSSขโมย CookieSanitize HTML
CSRFหลอกให้ทำ actionCSRF Token
// ❌ อันตราย!
const query = `SELECT * FROM users WHERE id = ${userId}`;
// ✅ ใช้ Parameterized Query
const query = `SELECT * FROM users WHERE id = $1`;
await db.query(query, [userId]);
// ❌ อันตราย!
<div dangerouslySetInnerHTML={{ __html: userInput }} />
// ✅ Sanitize HTML
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />

Material Selection (เลือกสเปกวัสดุ)

Section titled “Material Selection (เลือกสเปกวัสดุ)”
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 นาที
max: 100, // สูงสุด 100 requests
});
app.use('/api/', limiter);
import { z } from 'zod';
const UserSchema = z.object({
email: z.string().email('อีเมลไม่ถูกต้อง'),
password: z.string()
.min(8, 'ต้องมีอย่างน้อย 8 ตัว')
.regex(/[A-Z]/, 'ต้องมีตัวพิมพ์ใหญ่'),
});
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
  1. Principle of Least Privilege — ให้สิทธิ์เท่าที่จำเป็น
  2. Defense in Depth — หลายชั้นความปลอดภัย
  3. Keep Dependencies Updatednpm audit