การดู : 0

12/04/2026 18:16น.

JS2GO EP.49 Security สำหรับ Backend ด้วย Go และ Node.js

JS2GO EP.49 Security สำหรับ Backend ด้วย Go และ Node.js

#Authorization

#Authentication

#Backend

#Secure API Design

#Node.js

#Go

การสร้างระบบที่ “ปลอดภัยตั้งแต่วันแรก” ไม่ใช่การรอแก้ตอนข้อมูลรั่ว หรือระบบโดนเจาะ

 

ระบบ Backend ที่ดี ไม่ได้วัดกันแค่ว่า เร็วแค่ไหน แต่ต้องตอบคำถามสำคัญเหล่านี้ให้ได้อย่างมั่นใจ

  • ใครกำลังเรียก API นี้?
  • เขามีสิทธิ์ทำสิ่งนั้นจริงหรือไม่?
  • ข้อมูลที่ส่งเข้ามาปลอดภัยหรือยัง?
  • ระบบรับมือกับการโจมตีพื้นฐานได้หรือไม่?

 

บทความนี้จะพาคุณเข้าใจ Security Core ที่ทุกระบบ Production ต้องมี ทั้งฝั่ง Go และ Node.js

 

⭐ 1. Authentication vs Authorization (ต้องแยกให้ชัด)

 

หลายระบบพังเพราะ เอาสองอย่างนี้มาปนกัน

เรื่องความหมาย
Authentication (AuthN)คุณคือใคร?
Authorization (AuthZ)คุณทำอะไรได้บ้าง?

 

ตัวอย่าง

  • Login สำเร็จ → Authentication ผ่าน
  • เข้าหน้า Admin ไม่ได้ → Authorization ไม่ผ่าน

 

❗ AuthN ผ่าน ≠ มีสิทธิ์ทำทุกอย่าง
สองเรื่องนี้ต้องออกแบบแยกกันเสมอ

 

⭐ 2. Authentication Methods ที่ใช้จริงใน Production

 

🔹 2.1 JWT (JSON Web Token)

เหมาะกับ

  • REST API
  • Mobile App
  • Microservices

 

คุณสมบัติ

  • Stateless
  • ส่ง token มากับทุก request
  • Scale ง่าย ไม่ต้องเก็บ session

 

Flow

Login → JWT → Authorization: Bearer <token>

 

Go (Fiber) JWT Middleware (แนวคิดที่ถูกต้อง)

func AuthMiddleware(c *fiber.Ctx) error {
    header := c.Get("Authorization")
    if header == "" {
        return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
            "error": "missing token",
        })
    }

    // Parse + verify JWT (signature, exp, iss)
    // set user info into context
    return c.Next()
}

 

Node.js (Express)

function auth(req, res, next) {
  const header = req.headers.authorization;
  if (!header) {
    return res.status(401).json({ error: "missing token" });
  }

  // verify JWT
  next();
}

 

ข้อควรระวัง

  • ต้องตรวจ exp, iss, aud
  • อย่า trust payload โดยไม่ verify signature

 

🔹 2.2 Session-based Authentication

เหมาะกับ

  • Web Application
  • Server-rendered app

 

ลักษณะ

  • Stateful
  • Server เก็บ session
  • Client ใช้ cookie

 

Production ต้องตั้งค่า

  • HttpOnly
  • Secure
  • SameSite=Strict | Lax

 

🔹 2.3 OAuth 2.0 / OpenID Connect

เหมาะกับ

  • Login ด้วย Google / GitHub
  • Third-party integration

 

ข้อดี

  • ระบบไม่ต้องเก็บ password
  • ลดความเสี่ยงจาก credential leak

 

⭐ 3. Authorization & RBAC (Role-Based Access Control)

 

RBAC = ควบคุมสิทธิ์ตาม “บทบาท”

Roleสิทธิ์
userอ่านข้อมูล
editorแก้ไข
adminจัดการทุกอย่าง

 

Go (Fiber)

func RequireRole(role string) fiber.Handler {
    return func(c *fiber.Ctx) error {
        if c.Locals("role") != role {
            return c.Status(403).SendString("Forbidden")
        }
        return c.Next()
    }
}

 

Node.js (Express)

function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return res.status(403).send("Forbidden");
    }
    next();
  };
}

 

✔ AuthN = ใคร
✔ AuthZ = สิทธิ์
อย่ารวมสองอย่างไว้ใน middleware เดียว

 

⭐ 4. Input Validation ด่านแรกของความปลอดภัย

 

❌ อย่าเชื่อข้อมูลจาก client เด็ดขาด

 

ข้อมูลที่ไม่ validate นำไปสู่

  • SQL Injection
  • XSS
  • Logic Bug

 

Go (Validator)

type CreateUserRequest struct {
    Email string `validate:"required,email"`
    Age   int    `validate:"gte=18"`
}

 

ใช้ go-playground/validator

 

Node.js (express-validator)

app.post(
  "/user",
  body("email").isEmail(),
  body("age").isInt({ min: 18 }),
  handler
);

 

⭐ 5. ป้องกันการโจมตีที่พบบ่อย

 

🔥 5.1 SQL Injection

❌ อันตราย

SELECT * FROM users WHERE email = '${email}'

 

✅ ปลอดภัย

  • Prepared Statement
  • ORM / Query Builder

 

🔥 5.2 XSS (Cross-Site Scripting)

ป้องกันด้วย

  • Escape output
  • ไม่ render HTML จาก user
  • ใช้ Content Security Policy (CSP)

 

🔥 5.3 CSRF

ป้องกันด้วย

  • CSRF Token
  • SameSite Cookie
  • ตรวจ Origin / Referer

 

⭐ 6. Security Best Practices (Production Checklist)

 

✔ Hash password ด้วย bcrypt / argon2
✔ ห้าม log password / token
✔ HTTPS เท่านั้น
✔ Rate limit (กัน brute-force)
✔ Secret ผ่าน environment variable
✔ Rotate token / secret
✔ Principle of Least Privilege
✔ แยก role ชัดเจน
✔ ตรวจ dependency vulnerability (npm audit / govulncheck)

 

⭐ 7. Security Architecture (ภาพรวม)

 

Client
 → Authentication
   → Authorization (RBAC)
     → Input Validation
       → Business Logic
         → Database

 

Security ที่ดี = หลายชั้น
ไม่ใช่หวังพึ่ง layer เดียว

 


 

📌 สรุป

 

Security ไม่ใช่ feature เสริม แต่คือ รากฐานของระบบ Production

 

ถ้าคุณออกแบบ

  • Authentication ถูก
  • Authorization ชัด
  • Validation ครบ

 

คุณจะ

  • ลดความเสี่ยงอย่างมหาศาล
  • ไม่ต้องไล่แพตช์ตอนโดนโจมตี
  • ระบบอยู่รอดในระยะยาวจริง

 

🔵 ตอนต่อไป (ตอนสุดท้ายของซีรีส์): EP.50 Deploy Application: Go vs Node.js (Production Guide)

 

  • Build & Deploy
  • Docker / Multi-stage
  • Secrets & Environment
  • CI/CD
  • Zero-downtime
  • Production Checklist