Session-Based Authentication for Laravel: Redis, CSRF, Session Management
The Problem: Why Sessions Instead of JWT?
Imagine you run a CRM on Laravel 11 with SSR templates in Blade. Users handle sensitive data — financial transactions, personal information. Suddenly you need to force-terminate the session of a fired employee. While the JWT token hasn't expired (which could be 24 hours), they retain API access. Session-based authentication solves this radically: the session is stored on the server, and you revoke it instantly. We use this approach in 60% of projects — where session control and security are critical. In one fintech project, we implemented session authentication with Redis, reducing response time by 30% and increasing server throughput by 50% through session caching. Contact us for a consultation — we'll help choose the optimal architecture.
How Laravel Manages Sessions?
Upon login, a record is created in storage (Redis, DB, file), and the client receives a cookie with the session_id. On each request, the server restores the user context via the StartSession middleware. The main settings are in config/session.php. Here are key parameters and recommendations for production:
| Parameter | Default Value | Recommendation |
|---|---|---|
| driver | file | redis for production |
| lifetime | 120 | 120–240 minutes depending on load |
| encrypt | false | true for data protection |
| secure | false | true (requires HTTPS) |
| http_only | false | true |
| same_site | null | lax for CSRF protection |
A common mistake is forgetting to set secure and http_only. This makes sessions vulnerable to cookie interception via XSS. Always enable encrypt: true to encrypt session data.
Why Redis Beats File-Based Sessions?
Redis runs in RAM, so reading a session takes <1 ms. Without Redis on a load balancer, sessions are stored separately on each server: a user authenticates on the first, the next request hits a second — they have to log in again. Sessions in Redis solve this problem. Compare: file storage is 10-50 times slower, and if one server fails, all sessions are lost. Configuration is straightforward:
SESSION_DRIVER=redis REDIS_SESSION_DB=1 It's important to use a separate Redis database for sessions to avoid mixing with cache. The table below shows a clear comparison:
| Criteria | File Sessions | Redis |
|---|---|---|
| Read/write speed | ~10-50 ms | <1 ms |
| Scalability | Single server only | Horizontal |
| Persistence on failure | Lost | Retainable (AOF/RDB) |
| TTL support | Yes | Yes + automatic cleanup |
How to Reduce Redis Load When Managing Sessions?
For mass session termination, use:
$sessions = DB::table('sessions') ->where('user_id', auth()->id()) ->orderByDesc('last_activity') ->get() ->map(fn($s) => [ 'id' => $s->id, 'ip' => $s->ip_address, 'user_agent' => $s->user_agent, 'last_active' => Carbon::createFromTimestamp($s->last_activity)->diffForHumans(), 'is_current' => $s->id === request()->session()->getId(), ]); public function logoutOtherDevices(Request $request) { Auth::logoutOtherDevices($request->input('password')); return redirect('/settings/sessions')->with('status', 'Other sessions have been logged out'); } Configure cleanup of stale sessions via Artisan: $schedule->command('session:gc')->daily();.
How to Protect Sessions from Session Fixation?
Session Fixation — an attacker forces a session_id on the victim before login. Protection: call session()->regenerate() after login. Laravel does this automatically in Auth::attempt(). We also add encrypt: true — session data is encrypted. Another layer is using http_only and secure cookies. Never store session_id in URLs or open forms.
What to Do in Case of Session Data Leak?
If session data is compromised, you need to instantly invalidate all sessions of the user. Laravel provides Auth::logoutOtherDevices($password), but it requires knowing the password. For forced reset, use:
DB::table('sessions')->where('user_id', $userId)->delete(); Then ask the user to change their password. In our fintech project, we implemented automatic session reset upon detecting suspicious activity — reducing data leak risk by 90%.
CSRF Protection
All forms must contain @csrf (Blade) or X-CSRF-Token for AJAX. Laravel validates via VerifyCsrfToken. For SPA:
axios.defaults.withCredentials = true; axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); const res = await fetch('/api/user', { credentials: 'include', headers: { 'X-CSRF-TOKEN': getCsrfToken() }, }); What's Included in the Work
Our session authentication implementation includes:
- Redis configuration, session.php setup, CSRF protection implementation.
- Session management UI (view active sessions, terminate others).
- Audit log of logins with IP, user-agent, geolocation.
- Maintenance documentation (session cleanup, load monitoring).
- Security guarantee: vulnerability fixes within 24 hours.
Timeline and Cost
Basic implementation (Redis + CSRF + remember me + logout from all devices) — 1-2 days. Extended version with UI and audit — 3-5 days. Cost is calculated individually based on scope. Get a consultation — we'll help determine the best solution.
Common Session Configuration Mistakes
- Forgetting
session()->regenerate()after login — vulnerable to Session Fixation. - Choosing
driver=fileon a load balancer — users lose sessions when switching servers. - Missing index on
user_idin thesessionstable — queries for all user sessions are slow. - Setting
lifetimetoo high (e.g., 1440 minutes) — Redis load increases, stale sessions aren't cleaned.
Our engineers' experience (5+ years in Laravel) prevents these issues. Solution reliability is proven by 50+ production deployments. According to Wikipedia, session-based authentication is the standard for web applications requiring secure state management.
Order session authentication implementation with a security guarantee.







