laravel - 如何在 laravel 中使用 echo 服务器验证私人频道
问题描述
我正在尝试使用 laravel 回显服务器实现 WebSocket,并且我有一个私人频道,但我无法拥有经过身份验证的用户这是我的广播服务提供商
public function boot()
{
Broadcast::routes([
"middleware" => ['api','auth:api'],
]);
require base_path('routes/channels.php');
}
这是我的 bootstrap.js
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://127.0.0.1:6001',
authEndpoint: "/broadcasting/auth",
csrfToken: token
});
这是我的事件代码
class UserOnline implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
这是我的路线/channel.php
Broadcast::channel('presence-chat', function ($user) {
return true; //replace with suitable auth check here
});
Broadcast::channel('chat', function (User $user) {
return true;
});
这就是我收听活动的方式
Echo.join('chat')
.joining((user) => {
axios.put('/api/user/'+ user.id +'/online', {});
});
但我得到的只是这个
[4:42:50 PM] - 将身份验证请求准备到:http://localhost [4:42:50 PM] - 将身份验证请求发送到:http://localhost/broadcasting/auth
[4:42:50 PM] - 将身份验证请求准备到:http://localhost [4:42:50 PM] - 将身份验证请求发送到:http://localhost/broadcasting/auth
⚠ [下午 4:42:51] - lNRPHJfHfhzrp252AAAJ 无法通过 private-user.1 {"message":"Unauthenticated."} 客户端无法通过身份验证,获得 HTTP 状态 401 ⚠ [下午 4:42:51] - lNRPHJfHfhzrp252AAAJ 无法通过在线聊天身份验证 {"message":"Unauthenticated."} 客户端无法通过身份验证,获得 HTTP 状态 401
请问我有什么问题,我的错误在哪里?我浪费了几天时间寻找这个
解决方案
我将 localhost 和 ip 以及 APP_URL 和主机设置为0.0.0.0
然后我发送 CSRF 令牌。有时他们似乎有不同的目的地,所以我将它们设置在一个(0.0.0.0
)中并且它有效!
和 csrf 像这样:
window.Echo = new MyEcho({
broadcaster: 'socket.io',
host: '0.0.0.0:6001', // this is laravel-echo-server host
auth:{
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}}
});
推荐阅读
- r - 绘制加权有序 Logistic 回归的预测概率
- javascript - iPad打印整个页面而不是chrome中的目标div
- f# - F# 中有没有办法链接计算?
- pandas - iloc 搜索数据帧的替代方法
- regex - 如何在 kibana discover 中搜索以 g、b 或 a 开头的任何城市?
- apache-flink - 为什么 Flink 在 DataStream join + Global 窗口上发出重复记录?
- authentication - 将 react-django 暂存站点放在基本身份验证后面,但身份验证与端点的令牌身份验证冲突
- php - PHP数组选择无法正常工作
- internet-explorer - Tabulator 在 IE11 中选择编辑器错误
- swift - 快速解决冲突的结构值类型