Search code examples
laravel-5.4pusherlaravel-echo

Laravel Echo / Pusher authentication fails (403)


Learning Laravel event broadcasting / Echo / Vue and playing around with this tutorial.

I keep getting 403 responses to authentication, and I suspect my lack of understanding on the channels.php routes is the issue. I am using Player model instead of User for Auth which works ok.

Event ChatMessageSend

class ChatMessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $channel;
    public $player;
    public $chatMessage;

        /**
         * Create a new event instance.
         * GameChat constructor.
         * @param $chatMessage
         * @param $player
         */
        public function __construct(ChatMessage $chatMessage, Player $player)
        {
            $this->channel = session()->get('chat.channel');

            $this->chatMessage = $chatMessage;

            $this->player = $player;
        }

        /**
         * Get the channels the event should broadcast on.
         *
         * @return Channel|array
         */
        public function broadcastOn()
        {
            return new PrivateChannel($this->channel);
        }
    }

Listener ChatMessageNotification (default / empty)

class ChatMessageNotification
{
    /**
     * ChatMessageNotification constructor.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ChatMessageSent  $event
     * @return void
     */
    public function handle(ChatMessageSent $event)
    {
        //
    }
}

Controller ChatController

class ChatController extends Controller
{
    /**
     * Send chat message
     *
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getMessages(Request $request)
    {
        return ChatMessage::with('player')
            ->where('progress_id', '=', session('game.progress.id'))
            ->orderBy('created_at', 'DESC')
            ->get();
    }

    /**
     * Send chat message
     *
     * @param Request $request
     * @return array|string
     */
    public function sendMessage(Request $request)
    {
        $player = Auth::user();

        $message = $request->input('message');

        if ($message) {
            $message = ChatMessage::create([
                'player_id'   => $player->id,
                'progress_id' => session()->get('game.progress.id'),
                'message'     => $request->input('message')
            ]);
        }

        broadcast(new ChatMessageSent($player, $message))->toOthers();

        return ['type' => 'success'];
    }
}

Routes channels.php

Broadcast::channel(session()->get('chat.channel'), function ($player, $message) {
    return $player->inRoom();
});

And in my Player class

/**
 * A user can be in one chat channel
 */
public function inRoom()
{
    if ((Auth::check()) and ($this->games()->where('progress_id', '=', session('game.progress.id'))->get())) {
        return true;
    }

    return false;
}

When a player logs in, I store in session a chat room id which I would like to use as channel.

My vue chat instance is

Vue.component('chat-messages', require('./../generic/chat-messages.vue'));
Vue.component('chat-form', require('./../generic/chat-form.vue'));

const app = new Vue({
    el: '#toolbar-chat',

    data: {
        messages: []
    },

    created() {
        this.fetchMessages();

        Echo.private(chat_channel)
        .listen('chatmessagesent', (e) => {
            this.messages.unshift({
                message: e.data.message,
                player: e.data.player.nickname
            });
        });
    },

    methods: {
        fetchMessages() {
            axios.get(chat_get_route)
            .then(response => {
                this.messages = response.data;
            });
        },

        addMessage(message) {
            this.messages.unshift(message);

            this.$nextTick(() => {
                this.$refs.toolbarChat.scrollTop = 0;
            });

            axios.post(chat_send_route, message)
            .then(response => {
                console.log(response.data);
            });

        }
    }
});

But I keep getting

POST http://my-games.app/broadcasting/auth 403 (Forbidden)
Pusher : Couldn't get auth info from your webapp : 403

Solution

  • Error 403 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with

    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: 'your key',
        cluster: 'your cluster',
        encrypted: true,
        auth: {
            headers: {
                Authorization: 'Bearer ' + YourTokenLogin
            },
        },
    });
    

    And in app/Providers/BroadcastServiceProvider.php change by

    Broadcast::routes()
    

    with

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

    or

    Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT
    

    it worked for me, and hope it help you.