Hi guys, I've successfuly setup Laravel 11 w/ Sanctum and Reverb, my nuxt app (SPA outside of Laravel) can connect to a public WS channel, receiving events. Works well.
But I'm actually trying to connect to a private channel and I always get a 401 Unauthorized. I've followed the steps described in the Sanctum installation (moving the broadcasting routes https://laravel.com/docs/11.x/sanctum#authorizing-private-broadcast-channels) and using an authorizer for Echo.
For info I use https://nuxt.com/modules/nuxt-auth-sanctum that works well to automatically get CSRF token. Based on top of ofetch. All my HTTP API routes works well.
Do you have any clue on what's hapenning ? It's been multiple hours of debugging 😦
Thanks you very much
Here is my Nuxt plugin :
import Echo from 'laravel-echo'
import Pusher from 'pusher-js'
declare global {
interface Window {
Pusher:any;
Echo:any;
}
}
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig()
const client = useSanctumClient()
window.Pusher = Pusher
window.Echo = new Echo({
broadcaster: 'reverb',
key: config.public.reverb.appKey, // these are defined in my .env and works well when connecting to a public channel so it should be OK.
wsHost: config.public.reverb.host,
wsPort: config.public.reverb.port,
wssPort: config.public.reverb.port,
forceTLS: (config.public.reverb.scheme ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
authorizer: (channel, options) => {
return {
authorize: async (socketId, callback) => {
try {
const response = await client('/api/broadcasting/auth', {
method: 'post',
body: {
socket_id: socketId,
channel_name: channel.name
}})
callback(null, response)
} catch (error) {
callback(error)
}
}
}
},
})
})
window.Echo.private(`App.Models.User.${useSanctumUser().value.id}`)
.notification((notification) => {
console.log(notification)
})
Getting the error
{"message":"Unauthenticated."}
My app.php
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withBroadcasting(
__DIR__.'/../routes/channels.php',
['prefix' => 'api', 'middleware' => ['auth:sanctum']],
)
->withMiddleware(function (Middleware $middleware) {
$middleware->statefulApi();
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
My channels.php
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});