Laravel Broadcast - Combining multiple middleware (web, auth:api)

broadcasting in laravel
laravel broadcasting tutorial
laravel broadcast public channel
laravel broadcast private channel
laravel broadcast notifications
laravel broadcast redis
broadcasting/auth 403 forbidden
realtime laravel

I am using Laravel Event Broadcast and Pusher to utilize websockets both on my API and Web. If I try them individually, both work fine. What I mean is:

Broadcast::routes(['middleware' => 'web']); // this works for my Laravel website

Broadcast::routes(['middleware' => 'auth:api']); // this works for my api

However, if I want to use both at the same time like this:

Broadcast::routes(['middleware' => ['auth:api', 'web']]); // doesn't work

... it crashes for both, which I suspect that it is assuming I am trying to enable for both auth:api && web middlewares.

Is there a way to use an OR kind of statement for this (auth::api || 'web')? What if I want to use both at the same time and if it passes one middleware, it bypasses the middleware.

Please note that I am using Laravel Passport for my api.


Or is there a way to combine and creating a mixed middleware for both (which will essentially check for either api or web)? So I can use something like this maybe:

Broadcast::routes(['middleware' => 'broadcast']); // or auth:broadcast

Update:

As far as I understand, if I create a new Middleware called broadcast, I can do:

class BroadcastMiddleware() {

  public function handle() {
    $web = Auth::guard('web')->user();
    if ($web) {
        return response()->json($web);
    }

    $api = Auth::guard('api')->user();
    if ($api) {
        return response()->json($api);
    }
    return response()->json('Unauthorized.', 500);
  }
}

But then how do I change /broadcasting/auth route? If I try this:

Route::post('/realtime/auth', function(){
    return true;
})->middleware('broadcast');

This returns the user object info, however instead, it should return something like: auth:"374f7ff42b7da877aa35:c29addedec281b418331a61dc3cfc74da8b108222565fa4924a8..."

Why not just use something like this in the BroadcastServiceProvider? This creates two separate endpoints with separate middleware assigned.

    Broadcast::routes(['middleware' => 'web']);

    Broadcast::routes(['prefix' => 'api', 'middleware' => 'api']);

Laravel Boardcast, I am using Laravel Event Broadcast and Pusher to utilize websockets both on my API and Web. If I try them individually, both work fine. What I mean is: HTTP Middlewares provide a convenient mechanism for filtering HTTP requests entering your application. Laravel, for example, has a middleware for verifying a user's authentication. Some Middleware Use-Cases. These are some cases where I have had to resort to using middleware. There are many more cases where you would like to use a middleware.

I finally figured out how to do it.

I am not sure if it is the best way of achieving this, and I'd highly appreciate any improvements.

How I achieved is created a new middleware for 'web' and left the other one as it it. Here are the steps.

1) In 'BroadcastServiceProvider', left only auth:api guard for Broadcast::routes(['middleware' => 'auth:api']);.

This way, Laravel's auth:api method for authenticating broadcasting works as expected.

2) Created a middleware called "Broadcast" and mapped it in Kernel.php like so:

'broadcast' => \App\Http\Middleware\Broadcast::class

and the Broadcast.php middleware looks like this:

public function handle($request, Closure $next)
{
    $web = Auth::guard('web')->user();
    if ($web) {
        return response()->json(\Illuminate\Support\Facades\Broadcast::auth($request));
    }

    return response()->json('Unauthorized.', 500);
}

3) Created a unique route other than Laravel's /broadcasting/auth in my routes>web.php

Route::post('/guard/broadcast/auth', function(\Illuminate\Support\Facades\Request $req){
    return true;
})->middleware('broadcast');

4) And then only on my blade, I use it like so:

<script>

let pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
    cluster: 'us2',
    encrypted: true,
    auth: {
        headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}"
        }
    },
    authEndpoint: '{{ env('APP_URL') }}' + '/guard/broadcast/auth',
});

let channel = pusher.subscribe('private-channel.{{ Auth::user()->id }}');

channel.bind('my-event', addMessage);

function addMessage(data) {
    console.log(data);
}

</script>

Two broadcasting auth routes for different middleware · Issue , I am using Laravel Event Broadcast and Pusher to utilize websockets both on my API and Web. If I try them individually, both work fine. What I mean is:  Laravel includes a middleware to rate limit access to routes within your application. To get started, assign the throttle middleware to a route or a group of routes. The throttle middleware accepts two parameters that determine the maximum number of requests that can be made in a given number of minutes. For example, let's specify that an

I'm preferable just using middleware that extends to both auth:api and web middlewares.

like what I posted in here: https://github.com/tlaverdure/laravel-echo-server/issues/266#issuecomment-365599129. So, I just maintenance 1 middleware if I wanted to change it in the future

AuthEndpoint middleware WEB + API · Issue #266 · tlaverdure , Laravel Version: 5.3. I can define Broadcast::routes(); for web or Broadcast::​routes( How i can define two broadcasting auth routes for web middleware and api middleware? Note: you can edit your posts on GH so no need to post multiple Successfully merging a pull request may close this issue. All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group

Routing - Laravel, fonctionne bien avec le middleware auth:api sur le mobile (avec le token /​laravel-broadcast-combining-multiple-middleware-web-authapi  Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php, which contains several well documented options for tweaking the behavior of the authentication services. At its core, Laravel's authentication facilities are

Laravel Passport - Laravel, These routes are assigned the web middleware group, which provides Routes defined in the routes/api.php file are nested within a route group by the Sometimes you may need to register a route that responds to multiple HTTP verbs. Nested groups attempt to intelligently "merge" attributes with their parent group. Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things. Documentation Watch Laracasts. Laravel Vapor is a serverless deployment platform for Laravel, powered by AWS. Launch your Laravel infrastructure on Vapor and fall in love with

Middleware - Laravel, Laravel makes API authentication a breeze using Laravel Passport, which provides If you would like to whitelist multiple redirect URLs for your client, you may The JSON API is guarded by the web and auth middleware; therefore, it may only A combination of a "code verifier" and a "code challenge" replaces the client  All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group

Comments
  • Great solution, used this myself. Although I had to specify the middleware as 'auth:api' to get it to work. Thanks!
  • @Sledmore glad I could help!
  • This seems waaaay more elegant than my solution. I didn't try it myself personally just yet though.
  • But, this approach didn't return me auth:"374f7ff42b7da877aa35:c29addedec281b418331a61dc3cfc74da8b108222565fa4924a8..." which is what the authenticator needs