Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use a custom authentication guard for the /broadcasting/auth route in Laravel 11
    Laravel 11 custom authentication guard broadcasting Laravel Echo configuration authentication channels


Can I use a custom authentication guard for the /broadcasting/auth route in Laravel 11


Yes, you can use a custom authentication guard for the `/broadcasting/auth` route in Laravel 11. Here's how you can do it:

1. Define your custom authentication guard in the `config/auth.php` file:

php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'custom' => [
        'driver' => 'session',
        'provider' => 'custom_users',
    ],
],

2. Specify the custom guard when defining the broadcast channel in the `routes/channels.php` file:

php
Broadcast::channel('private-channel.{userId}', function ($user, $userId) {
    return (int) $user->id === (int) $userId;
}, ['guards' => ['custom']]);

In this example, we're using the `custom` guard to authenticate the user for the `private-channel.{userId}` channel.

3. When a client attempts to subscribe to the private channel, Laravel Echo will send an HTTP request to the `/broadcasting/auth` route. Laravel will use the specified `custom` guard to authenticate the user.

4. If the user is authenticated using the `custom` guard, the authorization callback will be executed to determine if the user is authorized to access the channel.

By specifying the `guards` option when defining the broadcast channel, you can instruct Laravel to use your custom authentication guard for that specific channel.

Keep in mind that you need to ensure that your custom guard implementation is compatible with the authentication logic used in your application. The custom guard should be able to authenticate the user and provide the necessary user information for the authorization callback to work correctly.

Citations:
[1] https://laravel.com/docs/11.x/broadcasting
[2] https://github.com/laravel/framework/issues/16151
[3] https://laracasts.com/discuss/channels/laravel/broadcasting-auth-with-custom-auth-guard
[4] https://laracasts.com/discuss/channels/laravel/how-to-use-custom-guard-with-laravel-broadcasting
[5] https://stackoverflow.com/questions/53742241/laravel-what-is-the-usage-of-broadcasting-auth-when-we-can-authenticate-user-i