using laravel echo with laravel lighthouse to listen for subscriptions

Viewed 32

I'm running into some issues using laravel echo on a stand-alone vue3 app and a laravel api.

In my frontend I have the following configured:

const httpLink = new HttpLink({
  uri: import.meta.env.VITE_APP_GRAPHQL_URL,
});

const echo = new Echo({
  broadcaster: 'pusher',
  key: import.meta.env.VITE_PUSHER_APP_KEY.toString(),
  cluster: 'eu',
  forceTLS: true,
  disableStats: true,
  authEndpoint: import.meta.env.VITE_APP_GRAPHQL_URL + `/subscriptions/auth`,
  auth: {
    headers: {
      Accept: 'application/json',
      Authorization:
        'Bearer ' + CookieManager.get(import.meta.env.VITE_APP_ID_TOKEN_COOKIE?.toString() ?? '') ??
        undefined,
    },
  },
});

export const apolloClient = new ApolloClient({
  link: from([errorLink, authLink, httpLink]),
  cache: new InMemoryCache(),
});

export const subscriptionClient = new ApolloClient({
  link: from([authLink, createLighthouseSubscriptionLink(echo), httpLink]),
  cache: new InMemoryCache(),
});

which is than loaded into the main.ts file

app.provide(DefaultApolloClient, subscriptionClient);

Now, if I where to make any normal graphql queries that don't involve subscriptions they run as expected. but, if I run a subscription or listen to an event broadcasted from laravel itself I run into the following issue I receive a 403 forbidden error e.g. :

create a test event :

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct()
    {
    }

    public function broadcastOn(): Channel
    {
        return new PrivateChannel('test');
    }
}

create a test channel :

Broadcast::channel('test', function ($user) {
    return true;
});

Listen to this channel on the frontend

echo.private('test').listen('TestEvent', (e) => {
  console.log(e);
});

following error occurs :

Pusher :  : ["Error: Unable to retrieve auth string from channel-authorization endpoint - received status: 403 from http://localhost:8000/graphql/subscriptions/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/channels/server_api/authorizing-users/"]

I tried searching for some docs on how to use the graphql subscriptions AND the normal laravel broadcasting together but honestly after hours of searching my brain has melted.

1 Answers

The subscription authentication endpoint can only authenticate GraphQL subscriptions. It cannot authenticate normal broadcast events.

Related