laravel / reverb

Laravel Reverb provides a real-time WebSocket communication backend for Laravel applications.
https://reverb.laravel.com
MIT License
1.1k stars 89 forks source link

Subscription to private channel from Next.js using Laravel Breeze doesn't work. I keep getting unauthorized error #101

Closed KirinyetBrian closed 7 months ago

KirinyetBrian commented 7 months ago

Reverb Version

@beta

Laravel Version

11.0

PHP Version

8.3

Description

I keep getting this:
image

Browser error image

Subscribing to the private channel: image

The echo configuration: image

channel creation image

I have added this to the api/routes file: Broadcast::routes(['middleware' => ['auth:sanctum']]);

and when I log auth and data in this file i get null . Logged in user details doesn't reach this point :

image

Steps To Reproduce

Install Next.js install Laravel Breeze - Next.js Edition https://github.com/laravel/breeze-next

install Echo

configure echo tu use reverb

subscribe to private channel

joedixon commented 7 months ago

Hey @KirinyetBrian from your screenshot, it doesn't look like an auth token is being sent when subscribing to the channel. Is one being returned correctly from the api/broadcasting/auth endpoint?

KirinyetBrian commented 7 months ago

Hey @KirinyetBrian from your screenshot, it doesn't look like an auth token is being sent when subscribing to the channel. Is one being returned correctly from the api/broadcasting/auth endpoint?

@joedixon No I was not sending an auth token simply because the user is not authenticated via token but through cookie based session authentication so i assumed I did not need to send a token. On a closer look on the browser the api/broadcasting/auth doesnt return anything except an ok status 200. I am confused am I missing something? Must I explicitly send an auth token for authorization to happen even if I don't typically use sanctum token based auth : I followed what i in the docs about authenticating private channels and that was not mentioned kindly clarify https://laravel.com/docs/11.x/sanctum#authorizing-private-broadcast-channels image

I also configured a global axios as required:

import Axios from 'axios'
const axios = Axios.create({
    baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
    },
    withCredentials: true,
    withXSRFToken: true
})

export default axios

I event tried this which I don't believe should be the case but it didn't work still getting the same unauthorized error in reverb:

import Echo from "laravel-echo";
import axios from '@/lib/axios'
import Pusher from 'pusher-js';

const EchoConfig = () => {

    window.Pusher = Pusher;

    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: process.env.NEXT_PUBLIC_REVERB_APP_KEY,
        wsHost: window.location.hostname,
        wsPort: process.env.NEXT_PUBLIC_REVERB_PORT,
        wssPort: process.env.NEXT_PUBLIC_REVERB_PORT,
        forceTLS: (process.env.NEXT_PUBLIC_REVERB_SCHEME ?? 'https') === 'https',
        enabledTransports: ['ws', 'wss'],
        auth:
        {
            headers:
            {
                Authorization: 'Bearer 21|mqK0lskDPZ0aDVo8uau4MPOn40SZrBrJp3RtbX461744d6b8',

            }
        },

        authorizer: (channel, options) => {
            return {
                authorize: (socketId, callback) => {
                    axios.post('/api/broadcasting/auth', {
                        socket_id: socketId,
                        channel_name: channel.name

                    })
                        .then(response => {
                            console.log('success:' + response.data)
                            callback(false, response.data);
                        })
                        .catch(error => {
                            console.log('error:' + error)
                            callback(true, error);
                        });
                }
            };
        },
    })

}

export default EchoConfig;

and this got me error 419 image

KirinyetBrian commented 7 months ago

@joedixon I found the issue everything was configured fine . I was upgrading my project from laravel 10 to 11 apparently this was the issue in the .env file. I was using _BROADCASTDRIVER in the .env file but the broadcasting.php file from 11 seems to use _BROADCASTCONNECTION I overlooked that. I should have updated the .env file to match the default option in broadcasting.php or vice versa image

image

Now I can subscribe to private channel just fine and the auth you were asking about is now being passed correctly

image

image

karim-mesghouni commented 7 months ago

How can I get the auth token?

sorrell commented 6 months ago

This one also bit me! The Laravel Reverb docs should explicitly mention that either BROADCAST_DRIVER or BROADCAST_CONNECTION should be set to reverb. I was able to get Reverb running fine locally (using Sail) without needing to change this envvar from pusher, however, in my staging/VM environment, this needed to be set to reverb.

DeiverJC commented 6 months ago

Hello @KirinyetBrian Thanks to this issue I was able to solve my error. Can you give me a hint on how you are using your EchoConfig function in your nextjs project? Where should I call?

newelement commented 4 months ago

@KirinyetBrian Thanks for the save! Clutch play for me. I've been looking for the fix all over.

alalfakawma commented 3 months ago

How can I get the auth token?

I second this. We're trying to implement realtime connection with a Flutter app, and i'm not really sure where to get the auth token. I'm guessing it's the bearer token provided by sanctum but i'm not sure. Could you please elaborate? @KirinyetBrian