You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Broadcast如何实现web与auth:api中间件的或逻辑验证

Solution: Switching Laravel Broadcast Middleware Logic from AND to OR

Hey there, let's fix this broadcast auth issue you're facing!

You're right about the core problem: when you attach both web and auth:api middleware to your broadcast routes, Laravel enforces an AND logic—it requires the request to pass both middleware checks, which is impossible because web relies on session auth while api uses token-based auth. Here's how to implement the OR logic you need:

Step 1: Create a Custom Broadcast Auth Middleware

First, make a new middleware that checks if the request passes either web or api auth:

php artisan make:middleware BroadcastAuthMiddleware

Open the generated file (app/Http/Middleware/BroadcastAuthMiddleware.php) and update its handle method:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class BroadcastAuthMiddleware
{
    public function handle($request, Closure $next)
    {
        // Check if user is authenticated via web session
        if (Auth::guard('web')->check()) {
            return $next($request);
        }

        // Check if user is authenticated via api token
        if (Auth::guard('api')->check()) {
            return $next($request);
        }

        // If neither passes, reject the request
        abort(403, 'Unauthorized access to broadcast channel');
    }
}

Step 2: Register the Middleware

Add your new middleware to the route middleware list in app/Http/Kernel.php:

protected $routeMiddleware = [
    // ... existing middleware entries
    'broadcast.auth' => \App\Http\Middleware\BroadcastAuthMiddleware::class,
];

Step 3: Use the Custom Middleware for Broadcast Routes

Replace your existing middleware setup with the new broadcast.auth middleware.

If you're defining channels in routes/channels.php:

Broadcast::channel('your-channel-name', function ($user) {
    // Your channel authorization logic here
}, ['middleware' => 'broadcast.auth']);

Or if you're using a route group for broadcast routes:

Route::middleware('broadcast.auth')->group(function () {
    Broadcast::routes();
});

How This Works

This custom middleware first checks if the request is authenticated via the web guard (for your Web UI users with active sessions), then falls back to checking the api guard (for your API clients sending valid tokens). As soon as one check passes, it lets the request through—exactly the OR logic you wanted.

Just make sure your API clients are sending valid authentication tokens (e.g., Bearer tokens in the Authorization header) and your Web UI has active user sessions, and both should now work seamlessly with your broadcast setup.

内容的提问来源于stack exchange,提问作者senty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:49:33