Người dùng → Gửi username + password → Server
↓
Kiểm tra thông tin
↓
Tạo Session trong Session Store
{ sessionId: "abc123", userId: 42, expiry: ... }
↓
Server → Gửi Cookie "sessionId=abc123" → Trình duyệt lưu lại
Người dùng click "Xem đơn hàng" → Trình duyệt TỰ ĐỘNG gửi Cookie sessionId=abc123
↓
Server tra cứu trong Session Store
↓
Tìm thấy → Trả về dữ liệu đơn hàng ✅
Không tìm thấy → Redirect về /login ❌
sequenceDiagram
participant Browser as 🌐 Trình duyệt
participant Server as 🖥️ Server
participant Store as 🗄️ Session Store
Browser->>Server: POST /login (username, password)
Server->>Server: Xác minh thông tin
alt ✅ Đăng nhập thành công
Server->>Store: Tạo session (sessionId, userId, expiry)
Store-->>Server: OK
Server-->>Browser: 200 OK + Set-Cookie: sessionId=abc123
else ❌ Sai thông tin
Server-->>Browser: 401 Unauthorized
end
Note over Browser,Store: Người dùng tiếp tục sử dụng app...
Browser->>Server: GET /orders (Cookie: sessionId=abc123)
Server->>Store: Tra cứu sessionId=abc123
alt ✅ Session hợp lệ
Store-->>Server: userId=42, role=user
Server-->>Browser: 200 OK + Dữ liệu đơn hàng
else ⌛ Session hết hạn
Server-->>Browser: 302 Redirect → /login
end
Browser->>Server: POST /logout
Server->>Store: Xóa session abc123
Server-->>Browser: 200 OK + Xóa Cookie
Khó scale ngang (horizontal scaling): Nếu bạn có 3 server, session tạo ở server A sẽ không tồn tại ở server B → cần dùng Sticky Session hoặc Session Store tập trung (Redis).
Tốn tài nguyên server: Mỗi user đăng nhập = 1 bản ghi trong bộ nhớ/DB.
Không phù hợp cho API/Mobile: Mobile app không dùng Cookie theo cách trình duyệt làm — thường phải dùng JWT hoặc Token thay thế.
CSRF Risk: Vì Cookie được gửi tự động, cần phòng chống tấn công Cross-Site Request Forgery.
// Đăng nhập — tạo session
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Tạo session ID mới (tránh Session Fixation)
$request->session()->regenerate();
return redirect()->intended('/dashboard');
}
return back()->withErrors(['email' => 'Thông tin đăng nhập không đúng.']);
}
// Đăng xuất — hủy session
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate(); // Hủy session
$request->session()->regenerateToken(); // Tạo CSRF token mới
return redirect('/login');
}
// Middleware kiểm tra session
// Laravel tự xử lý qua middleware 'auth'
Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware('auth');