VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.3-guards

⇱ Guards | hypervel/auth | DeepWiki


Loading...
Menu

Guards

Purpose and Scope

Guards are the core authentication components in the hypervel/auth package. They implement the guard pattern to authenticate users using different strategies such as sessions, JWT tokens, or custom callbacks. This document provides an overview of how guards work, their common functionality, and how they interact with other authentication components.

For detailed information about specific guard implementations, see:

For information about how guards are created and managed, see AuthManager. For information about how guards retrieve user data, see User Providers.


What is a Guard?

A guard is responsible for authenticating users in an HTTP request. Each guard implements a specific authentication strategy but provides a consistent interface for checking authentication status, retrieving the authenticated user, and validating credentials.

All guards implement the Guard interface, which defines the core authentication methods:

MethodReturn TypeDescription
check()boolDetermine if a user is authenticated
guest()boolDetermine if the user is a guest (not authenticated)
user()?AuthenticatableGet the currently authenticated user
id()int|string|nullGet the ID of the authenticated user
validate(array $credentials)boolValidate credentials without persisting authentication
setUser(Authenticatable $user)voidManually set the authenticated user

Sources: src/Contracts/Guard.php1-39


Guard Architecture

The following diagram shows how guards fit into the authentication architecture:


Sources: src/AuthManager.php1-256 src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php1-116


Guard Resolution

Guards are created and managed by the AuthManager. When a guard is requested, the AuthManager:

  1. Checks the guard cache - Returns the existing guard instance if already resolved
  2. Reads guard configuration - Retrieves configuration from auth.guards.{name}
  3. Determines the driver - Identifies which guard type to create (session, jwt, custom)
  4. Creates the guard - Calls the appropriate factory method
  5. Caches the instance - Stores the guard for subsequent use within the same application lifecycle

The resolution process:


Sources: src/AuthManager.php60-91


Guard Types

The hypervel/auth package includes three built-in guard types:

SessionGuard

Session-based authentication for traditional web applications. Maintains state across requests using the session store.

Driver name: session
Factory method: AuthManager::createSessionDriver()
Implements: Guard, StatefulGuard
Dependencies: SessionContract from hypervel/session

See SessionGuard for detailed documentation.

JwtGuard

Stateless token-based authentication using JSON Web Tokens. Ideal for APIs and single-page applications.

Driver name: jwt
Factory method: AuthManager::createJwtDriver()
Implements: Guard
Dependencies: JWTManager from hypervel/jwt

See JwtGuard for detailed documentation.

RequestGuard

Callback-based authentication for custom authentication logic. Allows defining authentication strategies inline.

Driver name: Custom (registered via viaRequest())
Factory method: Custom closure provided to viaRequest()
Implements: Guard
Dependencies: None (uses callback)

See RequestGuard for detailed documentation.

Custom Guards

Applications can register custom guard drivers using AuthManager::extend():


Sources: src/AuthManager.php104-125 src/AuthManager.php132-137 src/AuthManager.php188-193


Guard Helpers Trait

All guard implementations use the GuardHelpers trait, which provides common functionality:

MethodDescription
authenticate()Retrieve the user or throw AuthenticationException
hasUser()Check if a user instance exists
guest()Check if the user is a guest
check()Check if the user is authenticated
id()Get the authenticated user's ID
getProvider() / setProvider()Access/modify the user provider
loginUsingId($id)Log in a user by their ID
validate($credentials)Validate credentials without authentication
hasValidCredentials($user, $credentials)Check if credentials match the user

The trait reduces code duplication and ensures consistent behavior across all guard types. Guards must implement the user() method and may optionally implement login() and attempt() for stateful authentication.

See GuardHelpers Trait for detailed documentation.

Sources: src/Guards/GuardHelpers.php1-116


User Resolution Flow

Guards authenticate users through a multi-step process:


Key steps:

  1. Request arrives - Guard receives authentication check
  2. Cache lookup - Guard checks Hyperf Context for cached user
  3. Strategy execution - Guard uses its specific authentication strategy
  4. User retrieval - Guard uses UserProvider to fetch user by identifier
  5. Database query - UserProvider queries the user storage
  6. User instantiation - UserProvider creates Authenticatable instance
  7. Cache storage - Guard caches user in Context for the request duration
  8. Return user - Guard returns the authenticated user

This flow ensures users are retrieved only once per request, even if authentication is checked multiple times.

Sources: src/Guards/GuardHelpers.php1-116 src/AuthManager.php1-256


Interaction with User Providers

Guards delegate all user data operations to UserProvider implementations. This separation allows guards to focus on authentication logic while providers handle data retrieval:

Guard ResponsibilityUserProvider Responsibility
Parse authentication tokensRetrieve users by ID
Read session dataRetrieve users by credentials
Execute authentication callbacksValidate credentials
Cache user instancesCreate Authenticatable instances
Manage authentication stateQuery user storage

The GuardHelpers trait includes helper methods that interact with the provider:

Guards set their provider during construction and can be modified via setProvider().

See User Providers for detailed documentation about provider implementations.

Sources: src/Guards/GuardHelpers.php61-73 src/Guards/GuardHelpers.php85-114


Request-Scoped Caching

Guards use Hyperf Context to cache authentication data within the scope of a single request. This prevents redundant database queries when authentication is checked multiple times in the same request lifecycle.

What is Cached

Different guards cache different data:

Guard TypeCached Data
SessionGuardAuthenticated user instance
JwtGuardAuthenticated user instance, parsed token, JWT claims
RequestGuardAuthenticated user instance

Cache Keys

Guards use consistent cache key patterns to store data in Context:

  • User instances: Stored with guard-specific keys
  • Token data: Stored with token-specific keys
  • Claims data: Stored with claims-specific keys

Cache Lifecycle

The cache lifecycle follows the request lifecycle:

  1. Request starts - Context is empty
  2. First auth check - Guard authenticates, caches result
  3. Subsequent checks - Guard returns cached data
  4. Request ends - Context is cleared automatically

This ensures no data leaks between requests while maximizing performance within a request.

Sources: src/AuthManager.php52-54 src/AuthManager.php156-183


Guard Configuration

Guards are configured in the auth.php configuration file under the guards key. Each guard has a name and configuration array:


Configuration keys:

KeyRequiredDescription
driverYesGuard type: session, jwt, or custom
providerYesName of the user provider to use
Additional keysNoDriver-specific configuration options

The default guard is specified in auth.defaults.guard and can be overridden at runtime using AuthManager::setDefaultDriver().

See Configuration for complete configuration documentation.

Sources: src/AuthManager.php222-225 src/AuthManager.php154-183


Authentication Methods

All guards provide these core authentication methods through the Guard interface and GuardHelpers trait:

Checking Authentication Status


Retrieving the User


Validating Credentials


Manual Authentication


Note: Methods like login(), logout(), and attempt() are only available on stateful guards (SessionGuard). See StatefulGuard for details.

Sources: src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php1-116


Summary

Guards are the authentication engines of the hypervel/auth package:

  • Purpose: Authenticate users using different strategies
  • Interface: All implement the Guard contract
  • Types: SessionGuard, JwtGuard, RequestGuard, and custom guards
  • Creation: Managed by AuthManager using the factory pattern
  • Common Logic: Shared via the GuardHelpers trait
  • User Retrieval: Delegated to UserProvider implementations
  • Performance: Request-scoped caching via Hyperf Context
  • Extensibility: Custom guards via extend() and viaRequest()

For implementing specific authentication strategies, see the individual guard documentation pages: SessionGuard, JwtGuard, and RequestGuard.

Sources: src/AuthManager.php1-256 src/Contracts/Guard.php1-39 src/Guards/GuardHelpers.php1-116