VOOZH about

URL: https://deepwiki.com/hypervel/broadcasting/6.1-authentication-and-authorization

⇱ Authentication & Authorization | hypervel/broadcasting | DeepWiki


Loading...
Menu

Authentication & Authorization

Purpose and Scope

This document provides a detailed explanation of the authentication and authorization system within the Hypervel Broadcasting package. It covers how channel access is controlled, how users are authenticated, how authorization callbacks are registered and executed, and how the system integrates with authentication guards.

For information about defining broadcast channels in events, see Event Contracts. For details on channel naming conventions used by specific drivers, see Pusher Broadcaster and Redis Broadcaster.


Authentication System Overview

The broadcasting package implements a policy-based authorization model where channel access is controlled through registered callbacks. The system distinguishes between different channel types (public, private, presence, encrypted) and enforces authentication requirements accordingly.

Authentication Flow Diagram


Sources: src/BroadcastController.php1-32 src/Broadcasters/Broadcaster.php87-114 src/BroadcastManager.php74-114


Channel Types and Authentication Requirements

The broadcasting system recognizes four channel types, each with different authentication requirements:

Channel TypePrefix PatternAuthentication RequiredAuthorization CallbackUser Data Returned
PublicNoneNoNoNo
Privateprivate-*YesYesNo
Presencepresence-*YesYesYes (user info array)
Encryptedprivate-encrypted-*YesYesNo

Private and presence channels require both user authentication (via guards) and authorization (via registered callbacks). Public channels bypass all authentication checks.

Sources: src/Broadcasters/Broadcaster.php87-114


HTTP Authentication Endpoints

The broadcasting package provides HTTP routes for authenticating channel subscriptions. These endpoints must be registered before clients can access private or presence channels.

Channel Authentication Route

The primary authentication endpoint handles channel subscription requests:

POST /broadcasting/auth

Request Parameters:

  • channel_name: The channel the client wants to subscribe to
  • socket_id: The unique socket connection identifier

Registration:

The BroadcastManager::routes() method registers this endpoint src/BroadcastManager.php74-94:

  • Automatically includes web middleware
  • Excludes CSRF token verification by default
  • Registers across all configured HTTP kernels

User Authentication Route

Some broadcasters (Pusher, Ably) support user authentication for presence channels:

POST /broadcasting/user-auth

Registration:

The BroadcastManager::userRoutes() method registers this endpoint src/BroadcastManager.php100-114

Controller Implementation

Both routes are handled by BroadcastController src/BroadcastController.php1-32:

  • authenticate(): Delegates to Broadcast::auth($request)
  • authenticateUser(): Delegates to Broadcast::resolveAuthenticatedUser($request)

Sources: src/BroadcastManager.php74-124 src/BroadcastController.php1-32


Channel Authorization Registration

Channel authorization is configured by registering callback functions that determine whether a user can access a specific channel. The Broadcaster::channel() method provides this registration mechanism.

Registration Methods

Method Signature src/Broadcasters/Broadcaster.php72-84:

public function channel(
 HasBroadcastChannel|string $channel, 
 callable|string $callback, 
 array $options = []
): static

Registration Pattern Syntax:

Channels are registered using patterns with parameter placeholders:

  • Literal channel: 'order.1'
  • Parameterized channel: 'order.{orderId}'
  • Multiple parameters: 'chat.{roomId}.{userId}'
  • Wildcard patterns: Uses regex internally for matching

Storage Structure

Channel registrations are stored in static arrays src/Broadcasters/Broadcaster.php38-43:

protected static array $channels = []; // Pattern => Callback mapping
protected static array $channelOptions = []; // Pattern => Options mapping

This static storage allows all broadcaster instances to share the same channel registry.

Channel Registration Flow


Sources: src/Broadcasters/Broadcaster.php72-84 src/Broadcasters/Broadcaster.php38-43


Authorization Callbacks and Pattern Matching

When a client requests channel access, the broadcaster executes a multi-step process to find and execute the appropriate authorization callback.

Pattern Matching Process

Step 1: Pattern Iteration src/Broadcasters/Broadcaster.php94-97

The system iterates through registered patterns using channelNameMatchesPattern() src/Broadcasters/Broadcaster.php283-286:

preg_match('/^' . preg_replace('/\{(.*?)\}/', '([^\.]+)', $pattern) . '$/', $channel)

This converts 'order.{orderId}' to regex /^order\.([^\.]+)$/ for matching.

Step 2: Parameter Extraction src/Broadcasters/Broadcaster.php99

When a match is found, extractAuthParameters() src/Broadcasters/Broadcaster.php119-128 extracts named parameters from the channel name using extractChannelKeys() src/Broadcasters/Broadcaster.php165-170:

preg_match('/^' . preg_replace('/\{(.*?)\}/', '(?<$1>[^\.]+)', $pattern) . '/', $channel, $keys)

This captures named groups (e.g., orderId from order.123).

Step 3: Callback Normalization src/Broadcasters/Broadcaster.php101

The normalizeChannelHandlerToCallable() method src/Broadcasters/Broadcaster.php233-238 converts class strings to callable instances by resolving them from the container and calling their join() method.

Step 4: Callback Execution src/Broadcasters/Broadcaster.php103

The callback is invoked with:

  1. The authenticated user (first parameter)
  2. Extracted channel parameters (subsequent parameters)

Callback Return Values

The authorization callback can return src/Broadcasters/Broadcaster.php105-110:

Return ValueMeaningAction
falseExplicit denialThrows AccessDeniedHttpException
trueSimple approvalReturns valid authentication response
ArrayPresence channel dataReturns valid response with user data
Other truthyApprovalReturns valid authentication response
Falsy (not false)DenialThrows AccessDeniedHttpException

Authorization Execution Diagram


Sources: src/Broadcasters/Broadcaster.php92-114 src/Broadcasters/Broadcaster.php119-128 src/Broadcasters/Broadcaster.php165-170 src/Broadcasters/Broadcaster.php233-238 src/Broadcasters/Broadcaster.php283-286


Guard Support and User Retrieval

The broadcasting system integrates with Laravel's authentication system, supporting multiple guards for flexible authentication strategies.

User Retrieval Process

The retrieveUser() method src/Broadcasters/Broadcaster.php243-262 implements guard-aware user retrieval:

  1. Options Lookup: Retrieves channel options using retrieveChannelOptions() src/Broadcasters/Broadcaster.php267-278
  2. Guard Selection: Checks for guards key in options
  3. User Resolution:
    • If no guards specified: Uses default guard via AuthManager::user()
    • If guards specified: Iterates through guards array until user found
  4. Return Value: Returns authenticated user or null

Guard Configuration

Guards are specified when registering channel authorization src/Broadcasters/Broadcaster.php72:


Guard Resolution Flow


Sources: src/Broadcasters/Broadcaster.php243-262 src/Broadcasters/Broadcaster.php267-278


Implicit Model Binding

The broadcasting system supports implicit model binding for channel parameters, similar to route model binding in HTTP routing. This allows channel callbacks to receive model instances instead of raw parameter values.

Binding Resolution Process

Step 1: Parameter Reflection src/Broadcasters/Broadcaster.php121

The extractParameters() method src/Broadcasters/Broadcaster.php135-142 extracts type information from callbacks using reflection:

Step 2: Binding Detection src/Broadcasters/Broadcaster.php125

For each parameter, resolveBinding() src/Broadcasters/Broadcaster.php175-182 calls resolveImplicitBindingIfPossible() src/Broadcasters/Broadcaster.php189-206 which checks if binding is applicable using isImplicitlyBindable() src/Broadcasters/Broadcaster.php211-215:

return $parameter->getName() === $key
 && Reflector::isParameterSubclassOf($parameter, UrlRoutable::class);

Step 3: Model Resolution src/Broadcasters/Broadcaster.php198-200

If bindable, the system:

  1. Extracts class name via Reflector::getParameterClassName($parameter)
  2. Instantiates the model class
  3. Calls resolveRouteBinding($value) on the instance
  4. Throws AccessDeniedHttpException if model not found

Binding Requirements

For a parameter to be implicitly bound:

RequirementDetails
Parameter nameMust match channel placeholder name exactly
Type hintMust implement UrlRoutable interface
Model methodMust implement resolveRouteBinding() method

Implicit Binding Example Flow


Sources: src/Broadcasters/Broadcaster.php119-128 src/Broadcasters/Broadcaster.php135-160 src/Broadcasters/Broadcaster.php175-206 src/Broadcasters/Broadcaster.php211-215


User Authentication for Presence Channels

Presence channels require additional user authentication to broadcast user information to all channel subscribers. This is handled separately from channel authorization.

User Authentication Callback

The resolveAuthenticatedUserUsing() method src/Broadcasters/Broadcaster.php64-67 registers a callback for extracting user data:


User Resolution

When resolveAuthenticatedUser() is called src/Broadcasters/Broadcaster.php50-57:

  1. Checks if authenticatedUserCallback is set src/Broadcasters/Broadcaster.php33
  2. If set, invokes callback with request object
  3. Returns array of user data or null

This user data is sent to the broadcaster service (Pusher, Ably) and broadcast to presence channel subscribers.

Controller Integration

The BroadcastController::authenticateUser() method src/BroadcastController.php28-31 provides the HTTP endpoint:


User Authentication Flow


Sources: src/Broadcasters/Broadcaster.php50-67 src/BroadcastController.php28-31 src/Broadcasters/Broadcaster.php33


Security Considerations

Access Control Best Practices

  1. Always Validate User: Ensure callbacks verify the authenticated user's identity
  2. Check Ownership: Verify user owns or has access to resources referenced in channel parameters
  3. Fail Closed: Return false for unauthorized access rather than relying on implicit denial
  4. Use Model Binding: Leverage implicit binding to automatically verify resource existence

Socket ID Verification

The socket ID parameter src/BroadcastManager.php129-134 prevents a broadcasting client from receiving its own broadcast. The socket ID is extracted from the X-Socket-ID header:


Broadcaster implementations use this socket ID when generating authentication responses to enable the "except current user" functionality.

CSRF Protection

The default route registration src/BroadcastManager.php77-80 excludes CSRF verification because WebSocket clients typically cannot provide CSRF tokens:


Authentication relies on the session-based authentication middleware instead.

Authorization Callback Security

RiskMitigation
Denial of ServiceKeep callbacks lightweight; avoid heavy database queries
Information LeakageReturn only true/false for private channels; minimal user data for presence
Parameter InjectionUse implicit model binding; validate raw parameters
Guard BypassConfigure explicit guards; avoid relying on default guard alone

Channel Pattern Security

Avoid overly broad patterns that could grant unintended access:


Sources: src/BroadcastManager.php74-94 src/BroadcastManager.php129-134 src/Broadcasters/Broadcaster.php92-114


Code Entity Reference

Key Classes and Methods

EntityLocationPurpose
BroadcastManager::routes()src/BroadcastManager.php74-94Registers /broadcasting/auth endpoint
BroadcastManager::userRoutes()src/BroadcastManager.php100-114Registers /broadcasting/user-auth endpoint
BroadcastController::authenticate()src/BroadcastController.php16-19Handles channel authentication requests
BroadcastController::authenticateUser()src/BroadcastController.php28-31Handles user authentication requests
Broadcaster::channel()src/Broadcasters/Broadcaster.php72-84Registers channel authorization callback
Broadcaster::verifyUserCanAccessChannel()src/Broadcasters/Broadcaster.php92-114Executes authorization logic
Broadcaster::retrieveUser()src/Broadcasters/Broadcaster.php243-262Retrieves authenticated user with guard support
Broadcaster::resolveAuthenticatedUser()src/Broadcasters/Broadcaster.php50-57Resolves user data for presence channels
Broadcaster::extractAuthParameters()src/Broadcasters/Broadcaster.php119-128Extracts and binds channel parameters

Static Storage

PropertyLocationPurpose
Broadcaster::$channelssrc/Broadcasters/Broadcaster.php38Stores pattern => callback mappings
Broadcaster::$channelOptionssrc/Broadcasters/Broadcaster.php43Stores pattern => options mappings
Broadcaster::$authenticatedUserCallbacksrc/Broadcasters/Broadcaster.php33Stores user data extraction callback

Sources: src/BroadcastManager.php1-468 src/BroadcastController.php1-32 src/Broadcasters/Broadcaster.php1-304

Refresh this wiki

On this page