- Laravel版本:5.3.*
- PHP 版本: 5.6.17
- 数据库驱动程序和版本: MySQL
描述:
根据Laravel 5.3文档,在专用或状态频道上广播事件时,在BroadcastServiceProvider
的引导方法中,必须提供一个回调,如果用户有权收听该频道,则解析广播外观方法channel
。此方法应返回布尔值。在BroadcastServiceProvider
方法boot
中,我们还应该包含Broadcast::routes()
,这些路由将定义客户端将调用以检查通道权限的身份验证路由。此路由方法可以接收要应用于路由的属性数组。现在它变得奇怪了。当客户端调用此路由时,无论我传递给Broadcast::channel
方法的回调是什么,它都会给我一个 403 禁止,除非(现在是最奇怪的部分)我向Broadcast::routes
提供了一个数组,其中包含一个名为prefix
的键和任何值。如果键不是前缀,它将返回到 403 禁止。
PusherBroadcaster 中的 HttpException .php第 42 行:
我的设置如下。我肯定做错了什么,但在我们很多人试图理解之后,我无法弄清楚。有人可以给出提示吗?
重现步骤:
我创建了一个简单的事件:
<?php
namespace AppEvents;
use AppModelsPresentation;
use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
class PresentationCreated implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $presentation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Presentation $presentation)
{
$this->presentation = $presentation;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('presentation');
}
}
我通过调用event(new PresentationCreated($presentation));
触发
我已经安装了"pusher/pusher-php-server": "^2.5.0"
并在推送器中创建了一个帐户。 我把我的推送凭据放在.env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=*****
PUSHER_APP_KEY=*****************
PUSHER_APP_SECRET=****************
PUSHER_APP_CLUSTER=**
在我的configbroadcast.php
中,我有:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'eu',
'encrypted' => true,
],
],
我的客户端:
this.Echo = new Echo({
broadcaster: 'pusher',
key: typeof handover.pak !== 'undefined' ? handover.pak : '',
cluster: 'eu'
});
this.Echo.private(`presentation`)
.listen('PresentationCreated', (e) => {
console.log(e, 'raposa')
});
最后是广播服务提供商:
<?php
namespace AppProviders;
use IlluminateSupportServiceProvider;
use IlluminateSupportFacadesBroadcast;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
//The commented line would make the authorization pass even if I return false bellow
//Broadcast::routes(['prefix' => 'I do not know what I am doing']);
/*
* Authenticate the user's personal channel...
*/
Broadcast::channel('presentation', function ($user) {
return false;
});
}
}
编辑
多亏@yazfield回答,我才能理解发生了什么。http 错误是由于$request->user()
为空。这是因为我没有传递我的路由命名空间正在使用的其他中间件。通过做Broadcast::routes(['middleware' => ['web', 'clumsy', 'admin-extra']]);
我能够解决问题。
这个Laravel问题也帮助我掌握了这个东西。
通过给routes
一个参数,你正在设置路由属性并覆盖默认为'middleware' => ['web']
的属性,这基本上意味着当你给出任何没有middleware
属性的数组时,你没有使用任何 Web 中间件,你没有验证 crsfToken...等。