Skip to content

บทที่ 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 (หน้างานก่อสร้าง)”
1. User Login (email+password)
2. Server ตรวจสอบ
3. Server ออก Token
4. User เก็บ Token
5. User ส่ง Token ทุก Request
6. Server ตรวจ Token → อนุญาต/ปฏิเสธ
import jwt from 'jsonwebtoken';
// สร้าง JWT
const token = jwt.sign(
{ userId: user.id, email: user.email, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// ตรวจสอบ JWT
const decoded = jwt.verify(token, process.env.JWT_SECRET);
FeatureSessionJWT
เก็บที่ไหนServerClient
Revoke ได้✅ ง่าย❌ ยาก
Scaleต้องมี Shared StoreScale ง่าย

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

Section titled “Material Selection (เลือกสเปกวัสดุ)”
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,
}),
],
};
// Login
await supabase.auth.signInWithPassword({
email: 'user@example.com',
password: 'password123',
});
// Get User
const { data: { user } } = await supabase.auth.getUser();
// Logout
await supabase.auth.signOut();

Architect’s Note (บันทึกสถาปนิก)

Section titled “Architect’s Note (บันทึกสถาปนิก)”
  1. อย่าเก็บ Password เป็น Plain Text — ใช้ bcrypt
  2. JWT ใน localStorage มีความเสี่ยง XSS — ใช้ HTTP-only Cookie
  3. Access Token ควรหมดอายุเร็ว — 15 นาที
  1. Multi-Factor Authentication (MFA)
  2. Rate Limiting — ป้องกัน Brute Force
  3. Session Timeout — ออกจากระบบอัตโนมัติ