Skip to content

Security

Tirapong Chaiyakun edited this page Sep 19, 2026 · 1 revision

ความปลอดภัย

JWT

สร้างโทเคน (payload ต้องมี sub)

$token = \Core\Security::createJwt([
    'sub' => (string) $user->id,
    'email' => $user->email,
], expiry: 3600);

JWT_SECRET ต้องยาวอย่างน้อย 32 ตัวอักษร

ตรวจในเส้นทาง

use Core\Middleware\JwtAuth;
use Core\Route;

Route::group('/api', ['middleware' => JwtAuth::class], function () {
    Route::get('/me', 'UserController@me');
});

ไคลเอนต์ส่ง Authorization: Bearer <token>
ถ้าไม่ผ่านระบบตอบ 401

ตรวจเอง

$payload = \Core\Security::verifyJwt($request->bearerToken() ?? '');

รหัสผ่าน

$hash = \Core\Security::hashPassword('secret');
\Core\Security::verifyPassword('secret', $hash);

ใช้ bcrypt cost 12

เข้ารหัส (Cipher)

$cipher = \Core\Cipher::fromEnv();
$hidden = $cipher->encrypt('ข้อมูลลับ');
$plain = $cipher->decrypt($hidden);

ENCRYPTION_KEY รับทั้ง hex และ base64
สร้างคีย์ใหม่ด้วย \Core\Cipher::generateKey()

อัลกอริทึมเริ่มต้นคือ AES-256-GCM

CORS

CORS_ORIGIN=* อนุญาตทุก origin
ตั้ง origin เฉพาะได้ใน .env หรือในโค้ด

\Core\Cors::origins(['https://app.example.com']);
\Core\Cors::credentials(true);

CSRF (หน้า HTML)

View::render ใส่ $csrf_token ให้อัตโนมัติ
ในฟอร์มใส่ hidden field ชื่อ csrf_token แล้วเรียก $this->validateCsrf()

REST API ที่ใช้ JWT ไม่ต้องใช้ CSRF

Session

\Core\Session::start();
\Core\Session::set('user_id', 1);
\Core\Session::get('user_id');
\Core\Session::flash('notice', 'บันทึกแล้ว');
\Core\Session::destroy();

คีย์ถูกเติมคำนำหน้าจาก SESSION_PREFIX

Header และ sanitize

ระบบใส่ security headers อัตโนมัติ
บน APP_ENV=prod จะมี CSP และ HSTS

\Core\Security::sanitize($input, 'email');
\Core\Security::sanitizeArray($data);

IP และ proxy

ค่าเริ่มต้นใช้แค่ REMOTE_ADDR
ตั้ง TRUST_PROXIES=true เฉพาะเมื่ออยู่หลัง reverse proxy ที่เชื่อถือได้

Clone this wiki locally