บทที่ 15: Authentication
“บ้านที่ไม่มีกุญแจ ใครก็เข้าได้”
The Blueprint (พิมพ์เขียว)
Section titled “The Blueprint (พิมพ์เขียว)”Authentication ตอบคำถาม 3 ข้อ:
- คุณคือใคร? (Identity) → Login
- คุณมีสิทธิ์ทำอะไร? (Authorization) → Permissions
- พิสูจน์ได้ไหม? (Verification) → Token/Session
Authentication = ระบบกุญแจบ้าน
The Construction Site (หน้างานก่อสร้าง)
Section titled “The Construction Site (หน้างานก่อสร้าง)”🔐 Auth Flow พื้นฐาน
Section titled “🔐 Auth Flow พื้นฐาน”1. User Login (email+password)2. Server ตรวจสอบ3. Server ออก Token4. User เก็บ Token5. User ส่ง Token ทุก Request6. Server ตรวจ Token → อนุญาต/ปฏิเสธ🎫 JWT (JSON Web Token)
Section titled “🎫 JWT (JSON Web Token)”import jwt from 'jsonwebtoken';
// สร้าง JWTconst token = jwt.sign( { userId: user.id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: '7d' });
// ตรวจสอบ JWTconst decoded = jwt.verify(token, process.env.JWT_SECRET);🍪 Session vs JWT
Section titled “🍪 Session vs JWT”| Feature | Session | JWT |
|---|---|---|
| เก็บที่ไหน | Server | Client |
| Revoke ได้ | ✅ ง่าย | ❌ ยาก |
| Scale | ต้องมี Shared Store | Scale ง่าย |
Material Selection (เลือกสเปกวัสดุ)
Section titled “Material Selection (เลือกสเปกวัสดุ)”⚡ NextAuth.js
Section titled “⚡ NextAuth.js”import NextAuth from 'next-auth';import GoogleProvider from 'next-auth/providers/google';
export const authOptions = { providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ],};🟢 Supabase Auth
Section titled “🟢 Supabase Auth”// Loginawait supabase.auth.signInWithPassword({ email: 'user@example.com', password: 'password123',});
// Get Userconst { data: { user } } = await supabase.auth.getUser();
// Logoutawait supabase.auth.signOut();Architect’s Note (บันทึกสถาปนิก)
Section titled “Architect’s Note (บันทึกสถาปนิก)”⚠️ ข้อควรระวัง
Section titled “⚠️ ข้อควรระวัง”- อย่าเก็บ Password เป็น Plain Text — ใช้ bcrypt
- JWT ใน localStorage มีความเสี่ยง XSS — ใช้ HTTP-only Cookie
- Access Token ควรหมดอายุเร็ว — 15 นาที
💡 Best Practices
Section titled “💡 Best Practices”- Multi-Factor Authentication (MFA)
- Rate Limiting — ป้องกัน Brute Force
- Session Timeout — ออกจากระบบอัตโนมัติ