I am trying to listen to a private channel via both web and API guard. The configuration below works fine on web guard. However, I seem to be having trouble with authorizing in API from SPA/React. I am using Laravel Passport as my guard API driver.
config
import Echo from "laravel-echo";
let e = new Echo({
broadcaster: "pusher",
key: KEY,
cluster: CLUSTER,
authEndpoint: `/broadcasting/auth`,
forceTLS: true,
auth: {
headers: {
Accept: "application/json",
Authorization: `Bearer ${TOKEN}`
}
}
});
How I try to subscribe in useEffect
useEffect(() => {
e.private("orders_36")
.listen(".OrderChange", (e) => {
console.log(e);
})
.subscribed((e) => console.log(e, "subscribed"))
.error((e) => console.log(e, "error"));
}, []);
The error I get
{type: "AuthError", error: "Unable to retrieve auth string from auth endpoint - received status: 405 from /broadcasting/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users", status: 405}
I uncommented BroadcastServiceProvider from config/app.php, then I have written the code below in BroadcastServiceProvider.
BroadcastServiceProvider.php
Broadcast::routes([
'middleware' => 'auth:web,api',
]);
routes/channels.php
Broadcast::channel('orders_{id}', function ($id) {
return Auth::guard('api')->id() == $id;
});
app/Events/OrderChange.php
class OrderChange implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $order;
public function __construct($order)
{
$this->order = $order;
}
public function broadcastOn()
{
return new PrivateChannel('orders_'.$this->order->user_id);
}
public function broadcastAs()
{
return 'OrderChange';
}
public function broadcastWith()
{
return [
'order' => $this->order,
];
}
}
The code for broadcast calling in Controller
broadcast(new OrderChange(OrderResource::make($order)))->toOthers();
I have searched everywhere but the solutions provided do not seem to work.