Why Laravel Authorizing Private Broadcast Channels is not working? "channels.php" not working

728 Views Asked by At

I'm trying to authorize a private channel.
I'm using Vue.js as SPA, Laravel Sanctum for auth, and Laravel for api.
As the Laravel's documentation, I wrote my channel callbacks on "channels.php" under "routes" folder. But it wasn't working. It was saying 403 when I tried to authenticate the channel. Then I moved my channel callbacks codes to "api.php" and it was working.
Could you please explain me why? I want to write my channel callbacks on "channel.php". I am using Laravel 8. Here are my simple codes.

This is inside my MessageSent event.

public function broadcastOn()
{
    return new PrivateChannel("message");
}

public function broadcastAs()
{
    return "message-sent";
}

These are the codes I moved to api.php because they aren't working inside channels.php.

Broadcast::channel('message', function ($user) {
    return true;
});

This is inside BroadcastServiceProvider. As I know, "channels.php" is included by boot() function and codes inside it should be working.

public function boot()
{
    Broadcast::routes();

    require base_path('routes/channels.php');
}

This is my Laravel echo code.

window.Echo = new Echo({
  broadcaster: "pusher",
  cluster: "ap1",
  encrypted: true,
  key: "my_key",
  authorizer: (channel) => {
    return {
      authorize: (socketId, callback) => {
        api.post('broadcasting/auth', {
            socket_id: socketId,
            channel_name: channel.name
        })
        .then(response => {
            callback(false, response.data);
        })
        .catch(error => {
            callback(true, error);
        });
      }
    };
  }
});

window.Echo.private("message").on("message-sent", (data) => {
  console.log(data);
})
1

There are 1 best solutions below

1
On

I know the answer now. It seems like BroadcastServiceProvider is commented in config/app.php by default. So, BroadcastServiceProvider is not working and as a consequence, channels.php is not working. I removed that comment and I can use channels.php now.