Session-Based Authentication
This example demonstrates a complete session-based authentication implementation using Stilmark Base's Session, Auth, AuthMiddleware, and CsrfMiddleware classes.
Table of Contents
Application Structure
/your-app
├── public/
│ └── index.php # Entry point
├── src/
│ ├── bootstrap.php # Application bootstrap
│ └── Middleware/
│ └── AppAuthMiddleware.php # Custom auth middleware
├── .env # Environment configuration
└── composer.jsonBootstrap & Configuration
.env Configuration
.env Configurationsrc/bootstrap.php
src/bootstrap.phpLogin Flow
Login Route Handler
Protected Routes
Custom Auth Middleware with Database Validation
Protected Route Example
CSRF Protection
Using CsrfMiddleware with Router
Manual CSRF Validation
JavaScript API Calls with CSRF
Logout
Logout Handler
Complete Code
public/index.php - Full Application
public/index.php - Full ApplicationSecurity Checklist
✅ Session Security
HttpOnly cookies enabled
Secure flag enabled (HTTPS only)
SameSite attribute set
Session ID regenerated after login
Complete session destruction on logout
✅ CSRF Protection
CSRF tokens on all forms
CSRF validation on all unsafe methods
Time-bucketed tokens with rotation
Origin/Referer validation
✅ Timeout Management
Idle timeout (30 minutes default)
Absolute timeout (8 hours default)
Automatic activity tracking
Session cleanup on timeout
✅ Authentication
OAuth2 state validation
Custom session validation
Database user status checks
Protected route enforcement
Testing the Application
1. Test Login Flow
2. Test Protected Routes
3. Test CSRF Protection
4. Test Timeout
See Also
Session - Session management utilities
Auth - OAuth2 authentication
AuthMiddleware - Authentication middleware
CsrfMiddleware - CSRF protection
Request - Request handling and CSRF tokens
Last updated