VOOZH about

URL: https://deepwiki.com/hypervel/auth/2.3.1-sessionguard

⇱ SessionGuard | hypervel/auth | DeepWiki


Loading...
Menu

SessionGuard

The SessionGuard is a stateful authentication guard implementation that manages user authentication through server-side sessions. It stores the authenticated user's identifier in the session and retrieves the full user object on each request, providing traditional session-based authentication suitable for web applications.

For information about other guard types, see Guards. For details on the shared guard functionality, see GuardHelpers Trait. For session-less JWT authentication, see JwtGuard.


Architecture Overview

The SessionGuard implements the StatefulGuard contract and integrates with Hyperf's session management and context systems to provide efficient, secure session-based authentication.

Class Structure


Sources: src/Guards/SessionGuard.php1-149 src/Guards/GuardHelpers.php1-116


Session Management

The SessionGuard stores only the user's authentication identifier in the session, not the complete user object. This approach balances security and performance.

Session Key Structure

PurposeKey FormatExample
Session storageauth.guards.session.{guardName}auth.guards.session.web
Context cache (started)auth.guards.{guardName}.result:{sessionId}auth.guards.web.result:abc123
Context cache (unstarted)auth.guards.{guardName}.unstartedauth.guards.web.unstarted

The sessionKey() method generates the session storage key, while getContextKey() and getUnstartedContextKey() generate context cache keys.

Sources: src/Guards/SessionGuard.php145-148 src/Guards/SessionGuard.php93-101

Session Security

The guard implements session regeneration as a security measure against session fixation attacks:


The updateSession() method at src/Guards/SessionGuard.php72-77 performs two operations:

  1. Stores the user identifier in the session
  2. Calls session->migrate(true) to regenerate the session ID and destroy the old session

Sources: src/Guards/SessionGuard.php62-77


Context Caching Mechanism

The SessionGuard implements a sophisticated two-level context caching system to optimize performance and handle edge cases with session initialization.

Caching Strategy


Sources: src/Guards/SessionGuard.php103-126

Why Two Context Keys?

The dual context key system handles a specific edge case in Hyperf's session lifecycle:

  1. Started Session Context (auth.guards.{name}.result:{sessionId}): Used when the session has been initialized. The key includes the session ID to ensure cache invalidation across different session IDs.

  2. Unstarted Session Context (auth.guards.{name}.unstarted): Used when the session hasn't been started yet but a user object needs to be cached (e.g., when setUser() is called before session initialization).

The setUser() method at src/Guards/SessionGuard.php135-143 demonstrates this logic:


Sources: src/Guards/SessionGuard.php93-101 src/Guards/SessionGuard.php135-143


Authentication Methods

The SessionGuard provides multiple authentication methods for different use cases.

Authentication Flow Comparison

MethodPersists to SessionReturnsUse Case
attempt()Yes (if $login=true)boolStandard login with credentials
login()YesvoidDirect login with user object
once()NoboolOne-time auth without persistence
loginUsingId()YesAuthenticatable|boolLogin by user ID
onceUsingId()NoAuthenticatable|boolOne-time auth by ID
validate()NoboolCredentials check only

Credential-Based Authentication

The attempt() method at src/Guards/SessionGuard.php30-43 implements the complete authentication flow:


Sources: src/Guards/SessionGuard.php30-43 src/Guards/GuardHelpers.php107-114

Direct Login

The login() method at src/Guards/SessionGuard.php62-67 accepts a user object directly:


Sources: src/Guards/SessionGuard.php62-67

Stateless Authentication

The once() and onceUsingId() methods provide authentication without session persistence:

These methods are useful for API endpoints that need temporary authentication or for validating credentials without establishing a session.

Sources: src/Guards/SessionGuard.php48-57 src/Guards/SessionGuard.php82-91


User Retrieval

The user() method at src/Guards/SessionGuard.php103-126 implements the complete user retrieval logic with exception handling:


Exception Handling

The user() method wraps session and provider operations in a try-catch block at src/Guards/SessionGuard.php116-123 If any exception occurs during session retrieval or user lookup, the method caches null and returns it gracefully. This prevents authentication errors from propagating as exceptions.

Sources: src/Guards/SessionGuard.php103-126


Logout Process

The logout() method at src/Guards/SessionGuard.php128-133 performs a complete cleanup:


This three-step process ensures:

  1. Unstarted session context cache is cleared
  2. Started session context cache is cleared
  3. User ID is removed from session storage

Sources: src/Guards/SessionGuard.php128-133


Integration with Other Components

UserProvider Integration

The SessionGuard depends on a UserProvider implementation (injected via constructor at src/Guards/SessionGuard.php20-25) for all user data operations:

OperationProvider MethodPurpose
Retrieve by IDretrieveById(id)Get user from session-stored ID
Retrieve by credentialsretrieveByCredentials(credentials)Find user for authentication
Validate credentialsvalidateCredentials(user, credentials)Verify password/credentials

For details on user provider implementations, see User Providers.

Sources: src/Guards/SessionGuard.php20-25

Session Service Integration

The guard requires a SessionContract implementation (from the hypervel/session package). Key session operations used:

MethodUsage in SessionGuardLine Reference
put(key, value)Store user IDsrc/Guards/SessionGuard.php74
get(key)Retrieve user IDsrc/Guards/SessionGuard.php117
remove(key)Clear user ID on logoutsrc/Guards/SessionGuard.php132
migrate(destroy)Regenerate session IDsrc/Guards/SessionGuard.php76
getId()Get session ID for context keysrc/Guards/SessionGuard.php95
isStarted()Check if session initializedsrc/Guards/SessionGuard.php137

Sources: src/Guards/SessionGuard.php20-25

GuardHelpers Trait

The SessionGuard uses the GuardHelpers trait at src/Guards/SessionGuard.php17 to provide standard guard methods:

MethodDescriptionSource
authenticate()Get user or throw exceptionsrc/Guards/GuardHelpers.php21-28
check()Check if authenticatedsrc/Guards/GuardHelpers.php77-80
guest()Check if not authenticatedsrc/Guards/GuardHelpers.php41-44
id()Get user identifiersrc/Guards/GuardHelpers.php49-56
hasUser()Check if user existssrc/Guards/GuardHelpers.php33-36
loginUsingId()Login by ID with sessionsrc/Guards/GuardHelpers.php85-94
validate()Validate credentials onlysrc/Guards/GuardHelpers.php99-102
hasValidCredentials()Internal credential validationsrc/Guards/GuardHelpers.php107-114

For details on these shared methods, see GuardHelpers Trait.

Sources: src/Guards/SessionGuard.php17 src/Guards/GuardHelpers.php1-116


Macroable Support

The SessionGuard includes the Macroable trait at src/Guards/SessionGuard.php18 allowing runtime method injection for custom functionality:


Sources: src/Guards/SessionGuard.php18


Complete Authentication Lifecycle


This diagram illustrates the complete lifecycle showing:

  1. Initial authentication with credential validation and session creation
  2. Session regeneration for security
  3. Subsequent requests with context caching and session retrieval
  4. Logout with comprehensive cleanup

Sources: src/Guards/SessionGuard.php1-149 src/Guards/GuardHelpers.php1-116