Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lumen middleware sort (priority)

I'm using "laravel/lumen-framework": "5.7.*"

I have two middlewares, first one AuthTokenAuthenticate that should be applied to all the routes, so its defined in bootstrap/app.php like

$app->middleware([
    App\Http\Middleware\AuthTokenAuthenticate::class
]);

Another middleware is defined like

$app->routeMiddleware([
    'auth.token' => Vendor\Utilities\Middleware\AuthToken::class
]);

and will only be applied to some specific routes.

I need auth.token to be executed first, then AuthTokenAuthenticate but I can't find the way to do it because Lumen executes $app->middleware routes first.

Laravel has $middlewarePriority which is exactly what I need, but how can I handle it in Lumen?

like image 523
Seva Kalashnikov Avatar asked Dec 20 '18 23:12

Seva Kalashnikov


1 Answers

I don't think this is possible in Lumen in the way you want to. What I suggest is using the middleware alongside the router group middleware options.


Remove the global middleware registration

/bootstrap/app.php

$app->middleware([
    //App\Http\Middleware\AuthTokenAuthenticate::class
]);

Add both middlewares to the route middleware

/bootstrap/app.php

$app->routeMiddleware([
    'auth.token' => Vendor\Utilities\Middleware\AuthToken::class,
    'auth.token.authenticate' => App\Http\Middleware\AuthTokenAuthenticate::class
]);

Create two route groups: one with just auth.token.authenticate and one group with both auth.token and auth.token.authenticate.

/routes/web/php

$router->get('/', ['middleware' => 'auth.token.authenticate', function () use ($router) {
    // these routes will just have auth.token.authenticate applied
}]);

$router->get('/authenticate', ['middleware' => 'auth.token|auth.token.authenticate', function () use ($router) {
    // these routes will have both auth.token and auth.token.authenticate applied, with auth.token being the first one
}]);

I think this is the cleanest way to get the desired effect.

like image 121
Govert Verschuur Avatar answered Nov 08 '22 01:11

Govert Verschuur