AuthMiddleware
The AuthMiddleware class provides generic authentication validation for routes, supporting both session-based and JWT token-based authentication. It includes automatic timeout management (idle and absolute) and is designed to be extended for custom validation logic.
Capabilities
Session-based authentication validation
JWT Bearer token authentication support
Idle timeout management (rolling timeout)
Absolute timeout management (maximum session lifetime)
Automatic activity timestamp updates
Extensible validation for custom business logic
Constructor
public function __construct(
string $authSessionKey = 'auth',
int $idleTimeout = 43200, // 12 hours
int $absoluteTimeout = 86400 // 24 hours
)Parameters
$authSessionKey: Session key where authentication data is stored (default:'auth')$idleTimeout: Idle timeout in seconds (default:43200= 12 hours)$absoluteTimeout: Absolute timeout in seconds (default:86400= 24 hours)
Public API
Returns true if the request is authenticated, false otherwise.
Protected Methods (For Extension)
How It Works
JWT Token Check: If an
Authorization: Bearer <token>header is present, validates the JWT tokenSession Existence: Checks if authentication session exists
Idle Timeout: Validates that the session hasn't been idle too long
Absolute Timeout: Validates that the session hasn't exceeded maximum lifetime
Activity Update: Updates the last activity timestamp (rolling timeout)
Custom Validation: Calls
validateSession()for extensible validation logic
Basic Example
Custom Timeout Example
Router Integration Example
Extending for Custom Validation
Projects can extend AuthMiddleware to add custom validation logic:
Timeout Behavior
Idle Timeout (Rolling)
Resets on every authenticated request
User is logged out if inactive for the specified duration
Default: 12 hours
Absolute Timeout (Fixed)
Does NOT reset on activity
User is logged out after the specified duration from login, regardless of activity
Default: 24 hours
Example Timeline
Security Notes
Automatic timeout enforcement: Both idle and absolute timeouts are checked on every request
Activity tracking: Last activity timestamp is automatically updated on successful validation
Session cleanup: Expired sessions are automatically cleared
JWT support: Bearer tokens are validated using the
JwtclassExtensible: Override
validateSession()to add custom business logic validation
See Also
Auth - For OAuth2 authentication
Session - For session management utilities
JWT - For JWT token handling
Middleware Example - Route protection examples
Last updated