Getting a 401 (Unauthorised) response from Pusher due to failed authentication using Laravel Sanctum.
[Error] Pusher : : ["Error: Unable to retrieve auth string from channel-authorization endpoint - received status: 401 from http://localhost:8000/broadcasting/auth. Clients must be authorized to join private or presence channels. See: https://pusher.com/docs/channels/server_api/authorizing-users/"]
The BroadcastServiceProvider
is using Sanctum authentication guard.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes(['middleware' => ['auth:sanctum']]);
require base_path('routes/channels.php');
}
}
On the frontend X-CSRF-TOKEN
is being passed in the header. I've tried changing this header to Bearer
and Authorization
but still getting the same 401 unauthorized response.
import axios from '@/lib/axios'
import Echo from 'laravel-echo'
import Pusher from 'pusher-js'
import Cookies from 'js-cookie'
export default async function echo() {
if (typeof window !== 'undefined') {
Pusher.logToConsole = true
// const csrf = () => axios.get('/sanctum/csrf-cookie')
const key = '<redacted>'
const pusherClient = new Pusher(key, {
cluster: 'eu',
forceTLS: true,
channelAuthorization: {
endpoint: 'http://localhost:8000/broadcasting/auth',
headers: {
Accept: 'application/json',
'X-CSRF-TOKEN': Cookies.get('XSRF-TOKEN'),
},
},
})
window.Echo = new Echo({
broadcaster: 'pusher',
client: pusherClient,
})
window.Echo.private('chat').listen(
'App\\Events\\PrivateMessageSent',
e => {
console.log(e)
},
)
}
}