VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.4-user-providers

⇱ User Providers | hypervel/auth | DeepWiki


Loading...
Menu

User Providers

Purpose and Scope

User providers abstract the retrieval of user data from storage systems during authentication. They decouple guards from specific data storage mechanisms, enabling guards to authenticate users without knowing whether they come from Eloquent models, raw database queries, or external APIs.

This document explains the UserProvider contract, its core responsibilities, and how providers integrate with guards. For detailed information about specific provider implementations, see EloquentUserProvider, DatabaseUserProvider, and Custom User Providers. For information about how guards use providers during authentication, see Guards.


The UserProvider Contract

User providers implement the UserProvider interface, which defines three core methods for user retrieval and credential validation.

Interface Definition

MethodParametersReturn TypePurpose
retrieveById$identifier (mixed)?AuthenticatableRetrieve a user by their unique identifier (typically primary key)
retrieveByCredentials$credentials (array)?AuthenticatableRetrieve a user by credential fields (e.g., email, username)
validateCredentials$user (Authenticatable), $credentials (array)boolVerify that the provided credentials match the user's stored credentials

The contract enforces a consistent interface that all providers must implement, enabling guards to work with any provider implementation interchangeably.

Sources: src/Contracts/UserProvider.php1-26


UserProvider Architecture

The following diagram shows the relationship between the UserProvider interface and its concrete implementations:


Sources: src/Contracts/UserProvider.php1-26 src/Providers/EloquentUserProvider.php17-189 src/Providers/DatabaseUserProvider.php15-98


Core Responsibilities

User Retrieval by Identifier

The retrieveById method fetches a user using their unique identifier, typically after a guard has extracted the user ID from a session or JWT token.

EloquentUserProvider Implementation:

  • Creates a new model instance
  • Builds a query using the model's configured authentication identifier name
  • Applies any registered query callback
  • Returns the first matching model or null

DatabaseUserProvider Implementation:

  • Queries the configured table directly using the database connection
  • Uses the find method assuming the identifier is the primary key
  • Wraps the result in a GenericUser object

Sources: src/Providers/EloquentUserProvider.php37-46 src/Providers/DatabaseUserProvider.php29-34

User Retrieval by Credentials

The retrieveByCredentials method locates a user based on credential fields provided during authentication attempts. This method explicitly excludes password fields from the query.

Credential Filtering:

Both built-in providers filter out any credential keys containing the word "password" before building queries. This prevents passwords from being used in WHERE clauses and ensures that password validation happens separately through validateCredentials.

Filtered credentials: ['email' => 'user@example.com']
Password excluded: ['password' => 'secret123'] // Not used in query

Query Building:

The providers support flexible credential matching:

Credential Value TypeQuery BehaviorExample
Simple scalarWHERE key = value['email' => 'user@example.com']
Array or ArrayableWHERE key IN (...)['role' => ['admin', 'editor']]
ClosureExecutes closure with query builder['custom' => fn($q) => $q->where(...)]

Sources: src/Providers/EloquentUserProvider.php51-80 src/Providers/DatabaseUserProvider.php39-72

Credential Validation

The validateCredentials method verifies that provided credentials match the user's stored credentials, typically by comparing password hashes.

Both EloquentUserProvider and DatabaseUserProvider delegate password verification to the HashContract implementation from the hypervel/hashing package. This ensures secure password comparison using timing-attack-resistant algorithms.

Validation Flow:

  1. Extract plain text password from credentials array: $credentials['password']
  2. Retrieve hashed password from user: $user->getAuthPassword()
  3. Verify using hasher: $hasher->check($plain, $hashed)
  4. Return boolean result

Sources: src/Providers/EloquentUserProvider.php97-102 src/Providers/DatabaseUserProvider.php91-97


Provider Authentication Flow

The following sequence diagram illustrates how guards interact with user providers during authentication:


Sources: src/Providers/EloquentUserProvider.php37-102 src/Providers/DatabaseUserProvider.php29-97


Built-in Provider Implementations

The package includes two built-in user provider implementations, each optimized for different use cases:

EloquentUserProvider

Uses Hyperf's Eloquent ORM for user retrieval, providing full model functionality including relationships, accessors, events, and query scopes.

Key Features:

  • Works with any Eloquent model implementing Authenticatable
  • Supports query callbacks via withQuery() for runtime customization
  • Enables eager loading of relationships
  • Provides full Eloquent query builder capabilities

Configuration Example:


For detailed information, see EloquentUserProvider.

Sources: src/Providers/EloquentUserProvider.php17-189

DatabaseUserProvider

Uses raw database queries without Eloquent, returning simple GenericUser objects. More lightweight but lacks model features.

Key Features:

  • Direct database queries via ConnectionInterface
  • No model instantiation overhead
  • Returns GenericUser objects (simple attribute arrays)
  • Suitable for simple authentication without model complexity

Configuration Example:


For detailed information, see DatabaseUserProvider.

Sources: src/Providers/DatabaseUserProvider.php15-98

Custom Providers

Developers can create custom provider implementations for specialized storage systems such as LDAP, external APIs, or NoSQL databases. See Custom User Providers for implementation guidance.


Password Hashing Integration

All built-in providers depend on the HashContract interface from the hypervel/hashing package for secure password operations. The hasher is injected via constructor and used exclusively in the validateCredentials method.

Hasher Management in EloquentUserProvider:

The EloquentUserProvider exposes methods to get and set the hasher instance, enabling runtime hasher replacement if needed:

MethodPurpose
getHasher()Returns the current HashContract instance
setHasher(HashContract $hasher)Sets a new hasher implementation

Security Considerations:

  • Password fields are never included in database queries during user lookup
  • Password comparison uses timing-attack-resistant algorithms
  • Plain text passwords are never stored or logged
  • Hashing responsibility is delegated to a dedicated service

Sources: src/Providers/EloquentUserProvider.php97-146 src/Providers/DatabaseUserProvider.php91-97


Provider Selection and Configuration

Guards specify which user provider to use through configuration. The AuthManager instantiates providers based on the guard's configuration and resolves them using the CreatesUserProviders trait.

Configuration Structure:

Each guard in config/autoload/auth.php references a provider by name:


Provider Resolution Process:

  1. Guard configuration specifies provider name (e.g., 'provider' => 'users')
  2. AuthManager looks up provider configuration by name
  3. Provider driver field determines implementation class
  4. Provider-specific parameters (e.g., model, table) are passed to constructor
  5. Instantiated provider is injected into the guard

Multiple Providers:

Different guards can use different providers, enabling flexible authentication strategies:


Sources: Inferred from architecture diagrams and guard implementations


UserProvider Method Contracts

The following table summarizes the contract requirements and expected behavior for each UserProvider method:

MethodInputOutputSide EffectsError Handling
retrieveByIdUser identifier (typically integer or string)Authenticatable instance or nullNone (read-only)Returns null if not found; should not throw exceptions
retrieveByCredentialsCredential array (excluding passwords from queries)Authenticatable instance or nullNone (read-only)Returns null if not found or credentials empty; should not throw exceptions
validateCredentialsUser instance and credential arraybool (true if valid)None (read-only)Should not throw exceptions for invalid credentials; returns false

Important Contract Guarantees:

  • User provider methods are read-only operations that do not modify state
  • Methods return null rather than throwing exceptions when users are not found
  • Password fields are never used in database queries during retrieveByCredentials
  • All user instances returned must implement the Authenticatable contract
  • Providers are stateless and can be safely reused across requests

Sources: src/Contracts/UserProvider.php1-26


Integration Points

User providers integrate with multiple components in the authentication system:

Guard Integration:

All guard types (JwtGuard, SessionGuard, RequestGuard) depend on user providers for user retrieval. Guards call provider methods during:

  • Initial authentication attempts
  • Token/session validation
  • User retrieval by identifier

For more information, see Guards and User Resolver.

AuthManager Integration:

The AuthManager creates and configures provider instances based on configuration. It uses the CreatesUserProviders trait to resolve provider implementations.

For more information, see AuthManager.

Authenticatable Contract:

All users returned by providers must implement the Authenticatable contract, which defines methods like getAuthIdentifier() and getAuthPassword().

For more information, see Authenticatable Contract.

Sources: Inferred from architecture diagrams and overall system design