Search code examples
laravelpusherlaravel-echo

Refresh JWT token before Laravel Echo authentication


My web front end can no longer authenticate to Laravel's broadcast authentication endpoint when my browser tab comes back from being in the background because my JWT token has expired. How can I fix this?

This is my current code:

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: '{{ config('broadcasting.connections.pusher.key') }}',
    cluster: 'eu',
    forceTLS: true,
    auth: {
        headers: {
            'Authorization': 'Bearer ' + keycloak.token
        }
    }
});

This is how I refresh my JWT token before calling other authenticated endpoints:

keycloak.updateToken(30).then(() => {
    axios({
        url: url,
        headers: {'Authorization': 'Bearer ' + keycloak.token},
        params: params
    }).then(response => {
        console.log(response.data);
    });
});

When looking at Echo's source code on Github it seems possible to register interceptors. Is that the right direction? It doesn't seem possible to place a callable into the auth object of Echo's connection options.

Anybody know how I can solve my problem?


Solution

  • The authentication can be customized per these docs: https://laravel.com/docs/9.x/broadcasting#customizing-the-authorization-request

    Therefore the answer is to refresh the JWT token inside the authorize callable.