VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.1-authmanager

⇱ AuthManager | hypervel/auth | DeepWiki


Loading...
Menu

AuthManager

The AuthManager class is the central factory for the authentication system, responsible for creating, caching, and managing guard instances. It implements the factory pattern to provide a unified interface for accessing different authentication guards (JWT, Session, Request) and handles runtime guard switching based on configuration.

This document covers the internal workings of the AuthManager factory. For information about the guards themselves, see Guards. For the user resolver integration, see User Resolver. For the contracts defining the factory interface, see Factory Contract.


Core Responsibilities

The AuthManager class src/AuthManager.php22-255 serves four primary functions:

ResponsibilityDescriptionKey Methods
Guard ResolutionCreates guard instances based on configuration, mapping driver names to implementationsguard(), resolve()
Guard CachingMaintains a local cache of guard instances to prevent duplicate instantiation$guards property
Custom Driver RegistrationAllows developers to register custom guard implementations at runtimeextend(), viaRequest()
Default Driver ManagementManages the active guard for the current request contextgetDefaultDriver(), shouldUse()

Sources: src/AuthManager.php22-255


Architecture Overview

The following diagram illustrates the AuthManager's position in the authentication system and its relationships with other components:

Diagram: AuthManager Component Relationships


Sources: src/AuthManager.php22-55 src/ConfigProvider.php18-22


Guard Resolution Process

The AuthManager resolves guards using a multi-step process that checks for custom creators, then falls back to built-in driver methods.

Diagram: Guard Resolution Flow


Sources: src/AuthManager.php60-91

Guard Method

The guard() method src/AuthManager.php60-65 is the primary entry point for obtaining guard instances:


Key behaviors:

  • If no name provided, uses the default driver from configuration or context
  • Implements guard caching: checks $guards array before creating new instances
  • Uses null coalescing assignment (??=) to cache and return in one operation

Sources: src/AuthManager.php60-65

Resolve Method

The resolve() method src/AuthManager.php72-91 performs the actual guard instantiation:

  1. Configuration Lookup: Retrieves guard config via getConfig($name) src/AuthManager.php222-225
  2. Custom Creator Check: If $customCreators[$driver] exists, calls it src/AuthManager.php78-80
  3. Built-in Driver Method: Constructs method name like createSessionDriver src/AuthManager.php82-86
  4. Exception Handling: Throws InvalidArgumentException if guard or driver not found src/AuthManager.php74-76 src/AuthManager.php88-90

Sources: src/AuthManager.php72-91 src/AuthManager.php222-225


Built-in Driver Creation

The AuthManager provides factory methods for the two primary guard implementations.

Session Driver Creation

The createSessionDriver() method src/AuthManager.php104-111 instantiates a SessionGuard:


Constructor arguments:

  • $name: Guard name from configuration
  • UserProvider: Created via CreatesUserProviders trait based on $config['provider']
  • SessionContract: Resolved from the dependency injection container

Sources: src/AuthManager.php104-111

JWT Driver Creation

The createJwtDriver() method src/AuthManager.php116-125 instantiates a JwtGuard:


Constructor arguments:

  • $name: Guard name from configuration
  • UserProvider: Created via CreatesUserProviders trait
  • JWTManager: JWT service from hypervel/jwt package
  • RequestInterface: Current HTTP request
  • $ttl: Token time-to-live from JWT configuration (default: 120 minutes)

Sources: src/AuthManager.php116-125


Custom Driver Registration

The AuthManager supports two methods for registering custom authentication mechanisms.

Extend Method

The extend() method src/AuthManager.php132-137 registers custom driver creators:


Usage pattern:


The closure receives:

  • $name: Guard name (e.g., 'api', 'web')
  • $config: Configuration array for this guard

Sources: src/AuthManager.php132-137

Via Request Method

The viaRequest() method src/AuthManager.php188-193 is a convenience wrapper for callback-based authentication:


This simplifies creating RequestGuard instances for custom authentication logic:


Sources: src/AuthManager.php188-193


Default Driver Management

The AuthManager maintains the currently active guard, which can be set globally via configuration or per-request via context.

Diagram: Default Driver Resolution


Sources: src/AuthManager.php154-183

Get Default Driver

The getDefaultDriver() method src/AuthManager.php154-161 retrieves the active guard name:


Resolution priority:

  1. Request context (Context::get('__auth.defaults.guard')) - set via shouldUse()
  2. Global configuration (auth.defaults.guard)

Sources: src/AuthManager.php154-161

Should Use Method

The shouldUse() method src/AuthManager.php166-175 sets the default guard for the current request:


Side effects:

  1. Stores guard name in request context via setDefaultDriver() src/AuthManager.php180-183
  2. Updates the user resolver callback to use the new default guard

This is typically called by the Authenticate middleware after successful authentication to set the active guard for the remainder of the request lifecycle.

Sources: src/AuthManager.php166-175 src/AuthManager.php180-183


User Resolver Integration

The AuthManager maintains a user resolver callback that provides the default authenticated user for the application. This resolver is used by other parts of the system (like the Gate) to determine the current user.

Diagram: User Resolver Flow


Sources: src/AuthManager.php41-54 src/AuthManager.php198-217

User Resolver Method

The userResolver() method src/AuthManager.php198-205 returns the active resolver:


Default resolver src/AuthManager.php52-54:


This default implementation retrieves the user from the specified guard (or default guard if none specified).

Sources: src/AuthManager.php52-54 src/AuthManager.php198-205

Resolve Users Using Method

The resolveUsersUsing() method src/AuthManager.php212-217 allows customizing the user resolver:


This is called by shouldUse() to ensure the resolver uses the newly set default guard.

Sources: src/AuthManager.php212-217


Guard Caching Strategy

The AuthManager implements a simple but effective caching strategy to prevent duplicate guard instantiation.

Cache LevelStorageScopeImplementation
Guard Cache$guards array propertyPer-AuthManager instancesrc/AuthManager.php29
Default Driver CacheRequest contextPer-requestsrc/AuthManager.php156-158
User Resolver CacheRequest contextPer-requestsrc/AuthManager.php200-202

Guard Instance Cache

Guards are cached in the $guards property src/AuthManager.php29:


The guard() method src/AuthManager.php64 uses null coalescing assignment:


Benefits:

  • Single guard instance per name per request
  • Guards can maintain internal state (e.g., cached user)
  • Prevents redundant configuration lookups and dependency resolution

Context-based Caching

The AuthManager uses Hyperf's Context system for request-scoped state:

Context values are automatically cleared between requests in Hyperf's coroutine environment.

Sources: src/AuthManager.php29 src/AuthManager.php64 src/AuthManager.php156-158 src/AuthManager.php182 src/AuthManager.php200-202 src/AuthManager.php214


Magic Method Delegation

The __call() magic method src/AuthManager.php251-254 provides a convenience layer for calling guard methods directly on the AuthManager:


Usage examples:

Direct CallDelegated Call
$authManager->guard()->check()$authManager->check()
$authManager->guard()->user()$authManager->user()
$authManager->guard('api')->attempt($credentials)N/A (requires explicit guard)

This allows treating the AuthManager as if it were the default guard, simplifying common authentication checks.

Sources: src/AuthManager.php251-254


Dependency Injection Configuration

The ConfigProvider class src/ConfigProvider.php13-34 registers the AuthManager with Hyperf's dependency injection container:


Container bindings:

InterfaceImplementationPurpose
AuthFactoryContractAuthManagerPrimary factory interface
GuardClosure returning default guardDirect guard injection
AuthenticatableUserResolverCurrent user resolution

The Guard::class binding enables direct injection of the default guard without manually calling guard():


Sources: src/ConfigProvider.php18-22


Configuration Integration

The AuthManager reads guard configurations from the auth.guards.* configuration namespace.

Expected configuration structure:


The getConfig() method src/AuthManager.php222-225 retrieves guard-specific configuration:


Each guard configuration must specify:

  • driver: The guard type (session, jwt, or a custom driver name)
  • provider: The user provider name (optional, falls back to default)

Sources: src/AuthManager.php222-225


Summary Table

AspectImplementationKey Code References
Primary InterfaceAuthFactoryContractsrc/AuthManager.php22
Guard Resolutionguard() and resolve() methodssrc/AuthManager.php60-91
Built-in DriverscreateSessionDriver(), createJwtDriver()src/AuthManager.php104-125
Custom Driversextend(), viaRequest()src/AuthManager.php132-137 src/AuthManager.php188-193
Default GuardContext-based with config fallbacksrc/AuthManager.php154-183
User ResolverClosure property with context overridesrc/AuthManager.php41-54 src/AuthManager.php198-217
Caching$guards array + Hyperf Contextsrc/AuthManager.php29 src/AuthManager.php64
Delegation__call() magic methodsrc/AuthManager.php251-254