How to authorize users to access private channels in Laravel Broadcasting using cookie authentication?

I am developing an application in Laravel that uses Broadcasting to implement real-time functionality using laravel/reverb. Currently, I am trying to authorize users to access private channels using cookie authentication.

Private channels require you to authorize that the currently authenticated user can actually listen on the channel. This is accomplished by making an HTTP request to your Laravel application with the channel name and allowing your application to determine if the user can listen on that channel."

The problem I am facing is that, although the users are successfully authenticated via cookies, they are not being allowed to access the private channels.

My configuration is as follows:

app/config/broadcasting.php

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Broadcast::routes(['prefix' => 'api/v1', 'middleware' => 'web']);

        require base_path('routes/channels.php');
    }
} 
Broadcast::channel('image-processed.{userId}', function (User $user, int $userId) {
    return $user->id === $userId;
});
class ImageProcessedEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    

    /**
     * Create a new event instance.
     */
    public function __construct(
        public GarmentDesign $garmentDesign
        )
    {
      
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('image-processed.' . $this->garmentDesign->user_id)
        ];
    }
}
import  Axios  from "axios";

const axios = Axios.create({
    baseURL: "http://localhost:8000/api/v1",
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
    },
    withCredentials: true,
    withXSRFToken: true,
});

export default axios;
window.Echo = new Echo({
        broadcaster: 'reverb',
        key: 'vemblmovqvr9lhdtagt5',
        wsHost: "localhost",
        wsPort: 8080,
        forceTLS: false,
        encrypted: true,
        disableStats: true,
        authorizer: (channel, options) => {
            return {
                authorize: (socketId, callback) => {
                    axios.post('broadcasting/auth', {
                        socket_id: socketId,
                        channel_name: channel.name
                    })
                        .then(response => {
                            callback(false, response.data);
                        })
                        .catch(error => {
                            callback(true, error);
                        });
                }
            };
        },
    });

    if (!auth.user) { await auth.getUser() }
    window.Echo.private(`image-processed.${auth.user.id}`)
        .listen('ImageProcessedEvent', async (e) => {
           console.log(e);
        });

401 Unauthorized

200 Ok with Bearer Token

Upvotes: 0

Views: 660

Answers (0)

Related Questions