Eran Machiels
Eran Machiels

Reputation: 881

Laravel broadcasting: private channels not working due to auth error

First of all I would like to say that I know there are really a lot of topics about this subject. I read them allmost all, but without succes.

I am using Laravel Echo and Pusher in order to make websockets work. This actually works, for normal (read: non-private) channels. I receive the Javascript object in good shape.

Where the problem starts, is when I try to send something on a private channel. I get in my console the following warning:
Pusher : Couldn't get auth info from your webapp : 500

This is due to a problem with authenticating the private channel, I guess. I tried to authenticate them in the following places:

BroadcastServiceProvider:

class BroadcastServiceProvider extends ServiceProvider
{

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

        /*
         * Authenticate the user's personal channel...
         */
        Broadcast::channel('notification.{userid}', function ($user, $userid) {
             return true;
        });
    }
}

or routes/channels.php:

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('notification.{userid}', function ($user, $userid) {
    return (int) $user->id === (int) $userId;
});

but none of this works. I also tried to change the wildcard to a *, instead of the {userid} but that doesn't work as well.

Pusher, though, shows the event in normal shape. So they are sent, only the receiving by Echo gives problems. My Echo configuration looks like this:

this.websocket = new Echo({
    broadcaster: 'pusher',
    key: 'KEY',
    cluster: 'eu',
    encrypted: false,
    authEndpoint: 'http://127.0.0.1:8000/broadcasting/auth'
});

this.id = 1;

this.websocket.private('notification.' + this.id).listen('CreditsSent', e => {
    console.log(e);
});

I am using Laravel 5.4 and PHP 7.x. Can someone please helpe, because I am lost.

Upvotes: 0

Views: 4421

Answers (2)

Eran Machiels
Eran Machiels

Reputation: 881

Figured it out myself. A while back, I updated my project from Laravel 5.3 to 5.4. I expected that channels.php, which I created manually, was imported automatically. Turned out that I had to import it within my broadcastServiceProvider. Everything works fine now :)

Upvotes: 5

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38962

Your application template must have <meta name="csrf-token" content="{{ csrf_token() }}"> in the head element or you can set window.Laravel.csrfToken before making a socket connection using Echo.

Ensure that Echo makes an authentication request that contains the CSRF-Token in the header.

You can verify this in the Network tab of your browser developer tools.

Upvotes: 0

Related Questions