I am getting 401 (Unauthorized) status for laravel private channel from reactJS.
This is working for userId=1 but returning 401 for all other users.
Here is the code for Laravel
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes([
"middleware" => ['api', 'jwt.auth'],
"prefix" => "api"
]);
require base_path('routes/channels.php');
}
}
class AppointmentEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $appointment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($appointment)
{
$this->appointment = $appointment;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('App.User.' . $this->appointment->patient_id);
}
}
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
And here is the react code
const token = JSON.parse(localStorage.getItem("patientToken"));
const options = {
broadcaster: 'pusher',
key: '1c**************61',
cluster: 'ap2',
encrypted: true,
authEndpoint: 'http://localhost/heal/api/broadcasting/auth',
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
},
},
};
window.Echo = new Echo(options);
var p = localStorage.getItem("patientId");
window.Echo.private(`App.User.${p}`).listen('ConfirmAppointmentEvent', (e) => {
alert("Doctor accepted your appointment")
console.log(e)
});
Working perfect for user_id 1, but not for others
I did uncomment App\Providers\BroadcastServiceProvider::class,
Laravel version 7.30.0
works for me
AuthEndpointController
public function auth(Request $request)
{
$pusher = new Pusher(env('PUSHER_APP_KEY'), env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'));
if($request->request->get('channel_name') === 'private-App.User.' . $request->user()->id) {
return $pusher->socket_auth($request->request->get('channel_name'), $request->request->get('socket_id'));
}
return response()->json([], 400);
}
const token = JSON.parse(localStorage.getItem("patientToken"));
const options = {
broadcaster: 'pusher',
key: '1c4c1546ef4c02340c61',
cluster: 'ap2',
forceTLS: true,
authEndpoint: 'http://localhost/heal/api/broadcasting/auth',
auth: {
headers: {
Authorization: `Bearer ${token}`,
},
},
};
window.Echo = new Echo(options);
var p = localStorage.getItem("patientId");
window.Echo.private(`App.User.${p}`).listen('ConfirmAppointmentEvent', (e) => {
alert("Doctor accepted your appointment")
console.log(e)
});