Laravel Echo私有频道认证返回401 Unauthorized问题求助
问题现象
- 普通频道下Reverb与Echo运行正常,但订阅私有频道时,
/broadcasting/auth路由返回401 Unauthorized,响应体为{"message":"Unauthenticated."} - 发起请求的用户已正常登录前端路由,但认证失败
已配置内容
1. 广播中间件设置(bootstrap/app.php)
return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__ . '/../routes/web.php', api: __DIR__ . '/../routes/api.php', commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware ->web(append: [ HandleInertiaRequests::class, AddLinkHeadersForPreloadedAssets::class, ]) ->trustProxies('*') ->validateCsrfTokens(); }) ->withBroadcasting('/../routes/channels.php', attributes: ['middleware' => ['api', 'auth:sanctum']]) ->withExceptions() ->create();
2. User模型广播配置
class User extends Authenticatable { use HasApiTokens; use HasFactory; use HasProfilePhoto; use Notifiable; use TwoFactorAuthenticatable; use BroadcastsEvents; ... public function broadcastOn($event): PrivateChannel { return new PrivateChannel('users.' . $this->id); } }
3. Echo前端配置
window.Echo = new Echo({ broadcaster: 'reverb', key: import.meta.env.VITE_REVERB_APP_KEY, wsHost: import.meta.env.VITE_REVERB_HOST, wsPort: import.meta.env.VITE_REVERB_PORT ?? 80, wssPort: import.meta.env.VITE_REVERB_PORT ?? 443, forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https', enabledTransports: ['ws', 'wss'], encrypted: true, authorizer: (channel, options) => { console.log('a'); return { authorize: (socketId, callback) => { console.log('b'); axios .post( '/broadcasting/auth', { socket_id: socketId, channel_name: channel.name, }, { withCredentials: true, headers: { Accept: 'application/json', }, } ) .then(response => { callback(false, response.data); }) .catch(error => { callback(true, error); }); }, }; }, });
4. 前端订阅代码
onMounted(() => { if (user.value) { window.Echo.private(`users.${user.value.id}`).listen( '.UserUpdated', (event: { model: UserData }) => { console.log('Received user update from reverb!', event); } ); } });
补充说明
- 使用Jetstream启动套件,未对默认配置做重大修改
channels.php为空- 已查阅Laravel Sanctum私有频道认证官方文档,问题未解决
内容的提问来源于stack exchange,提问作者dannypas00
相关产品推荐
相关产品推荐

