Search code examples
phplaravelsingle-page-applicationlaravel-echo

Authorizing broadcasting channel in an SPA


My project is divided into two apps: vue based client-side app and laravel based server-side rest api app. I have uncommented App\Providers\BroadcastServiceProvider::class, in the config/app.php file.

The default broadcasting authorization route is, /broadcasting/auth. Since it has a web middleware applied, it shows a 419 due to CSRF issue. So in the BroadcastServiceProvider I changed this:

Broadcast::routes();

to this:

Broadcast::routes(['middleware' => ['auth:api']]);

But now the problem is whenever I visit my client-side app, I get the following error in the console:

GET http://localhost:8000/v1/login 405 (Method Not Allowed)

How do I fix this?

My client side configuration:

window.Echo = new Echo({
    authEndpoint: 'http://localhost:8000/broadcasting/auth',
    broadcaster: 'pusher',
    key: 'anyKey',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true
});

window.Echo.private('test.1').listen('TestUpdated', (e) => {
    /*eslint-disable no-console*/
    console.log(e);
});

Solution

  • This is what I ended up doing in my api.php routes file:

    Route::post('/broadcast',function (Request $request){
        $pusher = new Pusher\Pusher(env('PUSHER_APP_KEY'),env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'));
        return $pusher->socket_auth($request->request->get('channel_name'),$request->request->get('socket_id'));
    });
    

    Then I changed the authEndpoint to that route in the client-side app:

    window.Echo = new Echo({
        authEndpoint: 'http://localhost:8000/broadcast',
        ...
    }