Session-Based Authentication Implementation for Web Application

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Session-Based Authentication for Web Applications

Session-based authentication is the classic approach: on login, a record is created in session storage, and the client receives a cookie with session_id. On each request, the server looks up the session by ID and restores the user context. Stateful—state is stored on the server. Reliable, simple to implement, easy to revoke.

When Sessions Are Better Than JWT

Sessions are preferable for:

  • Traditional web applications with SSR (Blade, Twig, ERB)
  • When instant logout is required (don't wait for token expiration)
  • Storing large state data without transmitting in cookies
  • Applications with limited user counts

JWT is preferable for:

  • APIs consumed by mobile applications
  • Microservice architecture
  • Horizontal scaling without centralized session storage

Laravel Session

// config/session.php — critical settings
return [
    'driver'          => env('SESSION_DRIVER', 'redis'), // redis/database/file
    'lifetime'        => 120,    // minutes
    'expire_on_close' => false,  // session survives browser close
    'encrypt'         => true,   // encrypt session data
    'secure'          => true,   // cookie via HTTPS only
    'http_only'       => true,   // inaccessible to JS
    'same_site'       => 'lax',  // CSRF protection
    'domain'          => '.example.com', // subdomains
];

Redis as session storage—scalable and fast. Without Redis, multiple servers cause user "disconnections" during load balancing:

# .env
SESSION_DRIVER=redis
REDIS_SESSION_DB=1  # separate Redis DB for sessions

Auth::login and Remember Me

public function login(LoginRequest $request)
{
    $credentials = $request->only('email', 'password');
    $remember = $request->boolean('remember');

    if (!Auth::attempt($credentials, $remember)) {
        throw ValidationException::withMessages([
            'email' => [trans('auth.failed')],
        ]);
    }

    $request->session()->regenerate(); // prevents Session Fixation

    return redirect()->intended('/dashboard');
}

public function logout(Request $request)
{
    Auth::logout();

    $request->session()->invalidate();    // deletes session
    $request->session()->regenerateToken(); // new CSRF token

    return redirect('/');
}

Remember me works via long-lived cookie with token hash—Laravel automatically restores the session on next visit.

Session Fixation and CSRF

Session Fixation: attacker injects session_id before login, then gains access after user logs in. Protection—session()->regenerate() immediately after successful login. Laravel does this automatically.

CSRF: all forms require @csrf (Blade) or X-CSRF-Token header for AJAX. Laravel verifies the token via VerifyCsrfToken middleware.

// Axios—automatically adds CSRF token
import axios from 'axios';
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
// Fetch API—cookies sent with credentials: 'include'
const res = await fetch('/api/user', {
  credentials: 'include',
  headers: { 'X-CSRF-TOKEN': getCsrfToken() },
});

Managing Multiple Devices

// Get all active sessions for user
$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(),
    ]);

// End all sessions except current
public function logoutOtherDevices(Request $request)
{
    Auth::logoutOtherDevices($request->input('password'));

    return redirect('/settings/sessions')
        ->with('status', 'Other sessions logged out');
}

Storing Sessions in Database

php artisan session:table
php artisan migrate
// config/session.php
'driver' => 'database',
'table'  => 'sessions',

Table sessions: id, user_id (nullable), ip_address, user_agent, payload (encrypted), last_activity.

Index on user_id is mandatory for "all user sessions" queries. Cleanup old sessions:

php artisan session:gc  # or via Scheduler

SPA + Laravel Sanctum (Cookie-Based)

For SPA where frontend and API are on the same domain—Sanctum in cookie mode is preferable to JWT:

// CSRF initialization
// Client: GET /sanctum/csrf-cookie — sets XSRF-TOKEN cookie
// After that all POST/PUT/DELETE requests automatically include token

Route::middleware('auth:sanctum')->get('/api/user', fn(Request $r) => $r->user());

Sanctum in cookie mode = sessions with additional protection. API tokens—separate Sanctum feature for mobile clients.

Timeline

Session authentication with Redis, remember me, CSRF protection, logout from all devices: 1–2 days. With session management UI, login audit log (IP, device, geolocation), suspicious login detection: 3–5 days.