VOOZH about

URL: https://deepwiki.com/auth0/wordpress/3-architecture

⇱ Architecture | auth0/wordpress | DeepWiki


Loading...
Menu

Architecture

This document provides an overview of the Auth0 WordPress Plugin's internal architecture, explaining its layered structure, core components, and integration patterns with WordPress and Auth0.

The plugin implements a layered architecture with distinct responsibilities:

For setup instructions, see Getting Started. For extending the plugin, see Development.

Layered Architecture

The plugin implements a four-layer architecture that separates concerns and maintains clear boundaries between WordPress integration, business logic, and Auth0 SDK interactions.

Architecture Layers Diagram


Sources: wpAuth0.php79-89 src/Plugin.php src/Hooks.php src/Actions/Base.php src/Database.php

Core Layer

The Core Layer manages plugin lifecycle, SDK initialization, and configuration retrieval.

Plugin Class Responsibilities

The Plugin class src/Plugin.php serves as the central orchestrator:

MethodPurposeReturns
getSdk()Returns configured Auth0 SDK instanceAuth0\SDK\Auth0
getConfiguration()Builds SDK configuration from WordPress optionsSdkConfiguration
run()Registers all action and filter classesself
database()Returns Database singletonDatabase
actions()Returns Hooks instance for actionsHooks
filters()Returns Hooks instance for filtersHooks
isEnabled()Checks if authentication is enabledbool
isReady()Validates minimum configuration existsbool

Singleton Pattern

The wpAuth0() function wpAuth0.php79-89 implements the singleton pattern, ensuring a single Plugin instance exists throughout the WordPress request lifecycle. The function accepts optional instances for testing purposes but defaults to creating a new Plugin instance.

SDK Configuration Builder

The importConfiguration() method src/Plugin.php274-329 constructs an SdkConfiguration object by:

  1. Reading configuration from wp_options table via getOption() methods
  2. Detecting execution context (WP_Cron vs. regular request) src/Plugin.php285-298
  3. Setting strategy to STRATEGY_REGULAR or STRATEGY_NONE based on context
  4. Configuring PSR-18/PSR-17 factories via Factory class src/Plugin.php289-293
  5. Optionally configuring token cache using WpObjectCachePool src/Plugin.php322-326

Sources: src/Plugin.php wpAuth0.php79-89

Action Layer

The Action Layer implements business logic through five specialized action classes that register WordPress hooks.

Action Class Registration Pattern


Each action class extends Base src/Actions/Base.php and defines a $registry array mapping WordPress hooks to methods. The register() method src/Actions/Base.php89-96 iterates this registry and calls addAction() for each hook.

Action Classes Overview

ClassPrimary HooksKey MethodsPurpose
Authenticationinit, login_form_login, login_form_logoutonInit(), onLogin(), onLogout()OAuth flow, session management, user resolution
Configurationadmin_init, admin_menuonMenu(), onSetup(), onUpdate*()Admin UI, settings registration, input sanitization
SyncAUTH0_CRON_SYNC, cron_schedulesonBackgroundSync(), updateCronSchedule()Background user synchronization, queue processing
UpdatesPlugin update hooksUpdate checkingVersion management, update notifications
ToolsAdmin tool hooksAdministrative utilitiesDiagnostic and maintenance tools

Hook Priority System

The Base::getPriority() method src/Actions/Base.php57-70 allows hook priorities to be configured via PHP constants (e.g., AUTH0_ACTION_PRIORITY_INIT), defaulting to priority 10.

Sources: src/Plugin.php224-245 src/Actions/Base.php src/Actions/Authentication.php src/Actions/Configuration.php src/Actions/Sync.php

Data Persistence

The Data Layer provides database abstraction and manages two custom tables for account linking and event queuing.

Database Class Interface


The Database class src/Database.php wraps WordPress's $wpdb global, providing:

Table Creation Strategy

Tables are created lazily via createTable() src/Database.php31-40 which uses WordPress's maybe_create_table() function to avoid redundant CREATE TABLE statements. Each action class calls createTable() before database operations to ensure tables exist.

For detailed schema information, see Architecture: Database Schema.

Sources: src/Database.php

Infrastructure Components

Hooks System

The Hooks class src/Hooks.php provides a unified interface for WordPress actions and filters:


The hookType property determines whether calls route to WordPress action or filter functions src/Hooks.php19-20 The Plugin class maintains separate singleton instances via actions() and filters() methods src/Plugin.php47-83

PSR-4 Autoloading

The plugin uses Composer's PSR-4 autoloader with the namespace Auth0\WordPress wpAuth0.php34-38 For production builds, dependencies are scoped under Auth0\WordPress\Vendor\ via PHP-Scoper to prevent conflicts with other plugins.

Activation Hook

The activation hook wpAuth0.php40-67 generates three cryptographic secrets using random_bytes(64) if they don't exist:

  • auth0_cookies.secret - Session encryption
  • auth0_backchannel_logout.secret - OIDC logout validation
  • auth0_authentication.fallback_secret - Emergency WordPress login

Sources: src/Hooks.php wpAuth0.php34-67 src/Plugin.php47-83

Configuration Management

Configuration is stored in wp_options using prefixed keys (auth0_*) and organized into logical groups.

Configuration Storage Pattern


Configuration Groups

Option KeyConfiguration GroupManaged ByExample Settings
auth0_clientClient credentialsConfiguration::onUpdateClient()Domain, Client ID, Secret
auth0_authenticationAuthentication behaviorConfiguration::onUpdateAuthentication()Session pairing, fallback settings
auth0_cookiesCookie configurationConfiguration::onUpdateCookies()Secret, domain, path, secure, SameSite
auth0_syncSynchronization settingsConfiguration::onUpdateSync()Database connection, schedule, push mode
auth0_accountsUser account handlingConfiguration::onUpdateAccounts()Matching strategy, missing user action

The Configuration class uses a declarative PAGES constant src/Actions/Configuration.php21-438 that defines the complete admin interface structure including pages, sections, fields, validation rules, and sanitizers.

For detailed configuration documentation, see Architecture: Configuration Management.

Sources: src/Actions/Configuration.php21-438 src/Plugin.php113-159

Integration Points

WordPress Integration

The plugin integrates with WordPress through:

Auth0 SDK Integration

The plugin wraps the Auth0-PHP SDK v8.18+ README.md11 configuring it with:

The SDK is accessed throughout the codebase via $this->getSdk() in action classes, which delegates to Plugin::getSdk() src/Plugin.php164-169

Sources: src/Plugin.php274-329 src/Actions/Authentication.php25-51 src/Actions/Configuration.php477-535 README.md11

Authentication Flow

The authentication system replaces WordPress's standard login with Auth0's Universal Login while maintaining WordPress session compatibility.


OAuth 2.0 Flow Implementation

The authentication flow is handled in Authentication::onLogin() src/Actions/Authentication.php433-551 which:

  1. Detects authentication parameters: Checks for code and state parameters src/Actions/Authentication.php474-477
  2. Exchanges authorization code: Uses $this->getSdk()->exchange() for token exchange src/Actions/Authentication.php485-501
  3. Resolves user identity: Maps Auth0 identity to WordPress user via resolveIdentity() src/Actions/Authentication.php517
  4. Establishes WordPress session: Sets authentication cookies and triggers login hooks src/Actions/Authentication.php530-534

Identity Resolution Strategy

The resolveIdentity() method src/Actions/Authentication.php660-724 implements a flexible matching strategy:

  1. Primary lookup: Search by Auth0 sub (subject) identifier in auth0_accounts table
  2. Email matching: For verified emails, optionally match existing WordPress users based on accounts.matching setting
  3. User creation: Create new WordPress users when accounts.missing is set to "create"

Session Pairing

Session pairing is enforced in Authentication::onInit() src/Actions/Authentication.php353-431 which:

  • Validates both WordPress and Auth0 sessions exist
  • Verifies the WordPress user matches the Auth0 connection
  • Handles token refresh when sessions.refresh_tokens is enabled
  • Clears invalid sessions and forces re-authentication

Sources: src/Actions/Authentication.php433-551 src/Actions/Authentication.php353-431 src/Actions/Authentication.php660-724

User Synchronization

The synchronization system maintains data consistency between WordPress and Auth0 through a background queue processing system built on WordPress cron.


Event Queuing System

WordPress user events are captured by Authentication action handlers and queued in the auth0_sync table:

Each event is serialized as JSON with a SHA-256 checksum to prevent duplicate processing src/Actions/Authentication.php283-287

Background Processing

The Sync::onBackgroundSync() method src/Actions/Sync.php214-254 processes queued events:

  1. Retrieves events: Selects up to 10 events from the sync queue src/Actions/Sync.php223
  2. Event filtering: Checks if each event type is enabled via sync_events configuration src/Actions/Sync.php225-229
  3. API synchronization: Calls appropriate Auth0 Management API endpoints
  4. Queue cleanup: Removes processed events from the queue src/Actions/Sync.php252

Cron Schedule Management

Custom cron schedules are registered in Sync::updateCronSchedule() src/Actions/Sync.php261-268:

  • AUTH0_SYNC schedule with configurable interval from sync.schedule option
  • AUTH0_MAINTENANCE schedule running every 5 minutes for cleanup tasks

Sources: src/Actions/Authentication.php270-308 src/Actions/Sync.php214-254 src/Actions/Sync.php261-268

Database Schema

The plugin extends WordPress's database schema with two custom tables for account linking and synchronization queuing.


Account Linking Table

The auth0_accounts table src/Database.php101-119 maintains the relationship between WordPress users and Auth0 identities:

FieldTypePurpose
idBIGINTPrimary key
siteTINYINTWordPress network site ID
blogBIGINTWordPress blog ID (multisite support)
userBIGINTWordPress user ID (foreign key to wp_users.ID)
auth0TEXTAuth0 connection identifier (sub field from JWT)

Synchronization Queue Table

The auth0_sync table src/Database.php121-141 queues user synchronization events for background processing:

FieldTypePurpose
idBIGINTPrimary key
siteTINYINTWordPress network site ID
blogBIGINTWordPress blog ID
createdINT(11)Unix timestamp of event creation
payloadTEXTJSON-encoded event data
hashsumVARCHAR(64)SHA-256 hash for duplicate prevention (unique key)
lockedINT(1)Processing lock flag

Database Operations

The Database class src/Database.php provides abstraction methods:

Sources: src/Database.php101-141 src/Database.php42-99

Security Model

The plugin implements multiple layers of cryptographic security for session management, authentication fallbacks, and backchannel logout functionality.

Security Secrets Management

Three types of secrets are generated during plugin activation wpAuth0.php42-66:

Secret TypeStorage LocationPurpose
Cookie Secretauth0_cookies.secretEncrypts session data in cookies/PHP sessions
Backchannel Logout Secretauth0_backchannel_logout.secretValidates OIDC backchannel logout tokens
Fallback Secretauth0_authentication.fallback_secretEnables WordPress login bypass via secret URL parameter

All secrets are generated using random_bytes(64) and stored as hexadecimal strings wpAuth0.php47

SDK Configuration Security

The Plugin::importConfiguration() method src/Plugin.php274-329 configures the Auth0 SDK with security parameters:

Authentication Fallback Mechanism

Emergency WordPress login access is provided via the auth0_fb URL parameter src/Actions/Authentication.php443-452 The fallback secret can be regenerated through the admin interface and is automatically updated when authentication settings are saved src/Actions/Configuration.php726-728

Backchannel Logout Security

OIDC backchannel logout src/Actions/Authentication.php454-468 validates incoming logout tokens using:

  • Secret-based URL parameter validation (auth0_bcl)
  • JWT signature verification via $this->getSdk()->handleBackchannelLogout()
  • Configurable token TTL for unclaimed logout events

Sources: wpAuth0.php42-66 src/Plugin.php274-329 src/Actions/Authentication.php443-468 src/Actions/Configuration.php726-758