VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.3.3-requestguard

⇱ RequestGuard | hypervel/auth | DeepWiki


Loading...
Menu

RequestGuard

Purpose and Scope

The RequestGuard provides callback-based authentication for custom authentication strategies. Unlike SessionGuard which uses persistent session storage or JwtGuard which uses JWT tokens, RequestGuard delegates authentication logic entirely to a user-provided callback function. This allows for flexible, application-specific authentication mechanisms such as API key validation, third-party authentication, or custom token schemes.

For general guard concepts and the GuardHelpers trait shared across all guards, see Guards Overview and GuardHelpers Trait. For authentication manager integration, see AuthManager.

Architecture Overview

The RequestGuard implements the Guard contract (not StatefulGuard) and uses the GuardHelpers trait for common authentication methods. It operates statelessly within a single request, relying on Hyperf's Context for request-scoped caching.


Sources: src/Guards/RequestGuard.php1-76

Core Components

Class Declaration and Interface Implementation

The RequestGuard class implements the Guard contract and includes both GuardHelpers and Macroable traits:

ComponentTypePurpose
GuardInterfaceBase guard contract defining authentication methods
GuardHelpersTraitProvides common methods like check(), authenticate(), guest()
MacroableTraitEnables dynamic method addition at runtime

The class does not implement StatefulGuard because it has no state persistence (no login/logout capabilities).

Sources: src/Guards/RequestGuard.php16-19

Constructor and Dependencies


The constructor accepts two parameters:

  1. $provider (src/Guards/RequestGuard.php32): A UserProvider instance for user data retrieval
  2. $callback (src/Guards/RequestGuard.php33): A callable that implements the authentication logic

The RequestInterface is automatically resolved from the DI container (src/Guards/RequestGuard.php36-37):


Sources: src/Guards/RequestGuard.php31-38

Authentication Callback

The authentication callback is the core of RequestGuard. It receives the UserProvider as an argument and must return either an Authenticatable user object or null:

Callback Signature:


The callback is invoked in the user() method (src/Guards/RequestGuard.php49):


The callback has full access to:

  • The UserProvider for database queries
  • The current request (via DI container)
  • Any custom logic for authentication

Sources: src/Guards/RequestGuard.php27-29 src/Guards/RequestGuard.php49

Context Caching

The RequestGuard uses Hyperf's Context to cache the authenticated user within a single request, preventing redundant callback invocations:


The context key is constant: 'auth.guards.request' (src/Guards/RequestGuard.php73). The caching mechanism is implemented in src/Guards/RequestGuard.php42-45:


Sources: src/Guards/RequestGuard.php40-56 src/Guards/RequestGuard.php71-74

Authentication Flow

The complete authentication flow for RequestGuard:


Exception Handling

If the callback throws an exception, it is caught and the result is cached as null (src/Guards/RequestGuard.php51-52):


This prevents cascading failures and ensures that failed authentication attempts don't repeatedly invoke the callback.

Sources: src/Guards/RequestGuard.php40-56

API Reference

Public Methods

MethodReturn TypeDescriptionSource
user()?AuthenticatableRetrieves authenticated user via callbacksrc/Guards/RequestGuard.php40-56
validate(array $credentials)boolValidates credentials (checks if user exists)src/Guards/RequestGuard.php61-64
setUser(Authenticatable $user)voidManually sets the authenticated usersrc/Guards/RequestGuard.php66-69

Inherited Methods from GuardHelpers

The following methods are provided by the GuardHelpers trait:

MethodReturn TypeDescriptionSource
authenticate()AuthenticatableReturns user or throws AuthenticationExceptionsrc/Guards/GuardHelpers.php21-28
check()boolReturns true if user is authenticatedsrc/Guards/GuardHelpers.php77-80
guest()boolReturns true if user is not authenticatedsrc/Guards/GuardHelpers.php41-44
hasUser()boolDetermines if guard has a user instancesrc/Guards/GuardHelpers.php33-36
id()int|string|nullReturns authenticated user's IDsrc/Guards/GuardHelpers.php49-56
getProvider()UserProviderReturns the user providersrc/Guards/GuardHelpers.php61-64
setProvider(UserProvider $provider)voidSets the user providersrc/Guards/GuardHelpers.php69-72

Sources: src/Guards/GuardHelpers.php1-116

Method: validate()

The validate() method in RequestGuard has a simplified implementation compared to other guards (src/Guards/RequestGuard.php61-64):


Note that the $credentials parameter is ignored. Validation simply checks if the callback returns a user. This differs from SessionGuard and JwtGuard, which perform actual credential validation through the UserProvider.

Sources: src/Guards/RequestGuard.php61-64

Comparison with Other Guards

Guard Capabilities Matrix

FeatureRequestGuardSessionGuardJwtGuard
InterfaceGuardStatefulGuardGuard
State PersistenceNoneSessionNone (stateless token)
Login Method
Logout Method✓ (token invalidation)
Credential ValidationCustom callbackDatabase + password hashToken signature
Context Caching
Custom LogicFull flexibilityFixed session logicFixed JWT logic
Use CaseAPI keys, custom authWeb applicationsAPIs, microservices

Key Differences

RequestGuard vs SessionGuard:

RequestGuard vs JwtGuard:

  • Both implement Guard (not StatefulGuard)
  • JwtGuard has specific token handling logic; RequestGuard delegates all logic to callbacks
  • JwtGuard has token invalidation; RequestGuard has no persistence

Sources: src/Guards/RequestGuard.php16-19 src/Guards/SessionGuard.php15-18

Use Cases and Examples

Conceptual Use Case: API Key Authentication

A typical use case for RequestGuard is API key authentication:


Conceptual Use Case: Third-Party Authentication

Another use case is integrating with external authentication services:

Callback Logic Flow:

  1. Extract bearer token from request
  2. Call external API to validate token
  3. Retrieve user information from external API
  4. Map external user to local Authenticatable user
  5. Return user or null

Conceptual Use Case: Multi-Factor Token Authentication

For custom multi-factor authentication:

Callback Logic Flow:

  1. Extract primary authentication token
  2. Extract secondary factor (e.g., TOTP code)
  3. Validate both factors
  4. Retrieve user from UserProvider
  5. Return user if both factors are valid

Integration with AuthManager

The RequestGuard is typically registered with the AuthManager in the configuration. The guard factory receives the callback:

Configuration Pattern:

  • Guard type: 'request'
  • Callback: Provided via configuration or runtime registration
  • UserProvider: Standard provider (Eloquent or Database)

For details on guard registration and resolution, see AuthManager.

Sources: src/Guards/RequestGuard.php1-76

Implementation Details

Request Resolution

The RequestInterface is resolved from the application container at construction time (src/Guards/RequestGuard.php36-37):


This ensures the guard always has access to the current HTTP request for extracting authentication credentials (headers, query parameters, etc.).

Context Key Strategy

Unlike SessionGuard which generates unique context keys per session (src/Guards/SessionGuard.php93-96), RequestGuard uses a static context key 'auth.guards.request' (src/Guards/RequestGuard.php73). This is acceptable because:

  1. RequestGuard is typically not used with multiple guard instances simultaneously
  2. Each request has its own context scope
  3. The guard has no persistent state to differentiate between instances

Thread Safety

The Context system in Hyperf provides coroutine-safe storage, ensuring that concurrent requests don't interfere with each other. Each coroutine has its own context, so cached users in RequestGuard are isolated per request.

Sources: src/Guards/RequestGuard.php40-74 src/Guards/SessionGuard.php93-96

Limitations and Considerations

No State Persistence

RequestGuard does not implement StatefulGuard, meaning:

  • No login() method available
  • No logout() method available
  • No attempt() method for credential validation
  • Cannot be used with middleware expecting stateful authentication

Callback Responsibility

The authentication callback is responsible for:

  • Extracting credentials from the request
  • Validating credentials
  • Returning the appropriate Authenticatable instance
  • Handling errors gracefully

Single Guard Instance

The static context key 'auth.guards.request' means that multiple RequestGuard instances in the same request will share the same cache. If you need multiple request guards, you should extend the class and override getContextKey().

Error Handling

Exceptions thrown by the callback are caught and result in null authentication (src/Guards/RequestGuard.php51-52). Consider logging errors within the callback if debugging is needed, as exceptions are silently suppressed.

Sources: src/Guards/RequestGuard.php1-76