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

  1. JWT Token Check: If an Authorization: Bearer <token> header is present, validates the JWT token

  2. Session Existence: Checks if authentication session exists

  3. Idle Timeout: Validates that the session hasn't been idle too long

  4. Absolute Timeout: Validates that the session hasn't exceeded maximum lifetime

  5. Activity Update: Updates the last activity timestamp (rolling timeout)

  6. 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

  1. Automatic timeout enforcement: Both idle and absolute timeouts are checked on every request

  2. Activity tracking: Last activity timestamp is automatically updated on successful validation

  3. Session cleanup: Expired sessions are automatically cleared

  4. JWT support: Bearer tokens are validated using the Jwt class

  5. Extensible: Override validateSession() to add custom business logic validation

See Also

Last updated