首页 > 解决方案 > 如何在 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

请问我有什么问题,我的错误在哪里?我浪费了几天时间寻找这个

标签: laravelwebsocketlaravel-echo

解决方案


我将 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()}}'
    }}

});

推荐阅读