首页 > 解决方案 > 流明中间件排序(优先级)

问题描述

我在用着"laravel/lumen-framework": "5.7.*"

我有两个中间件,第一个AuthTokenAuthenticate应该应用于所有路由,所以它的定义bootstrap/app.php如下

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

另一个中间件定义为

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

并且只会应用于一些特定的路线。

我需要auth.token先被执行,然后AuthTokenAuthenticate我找不到方法,因为 Lumen$app->middleware先执行路由。

Laravel 有$middlewarePriority这正是我需要的,但我如何在 Lumen 中处理它?

标签: phplaravelmiddlewarelumen

解决方案


我认为这在 Lumen 中不可能以您想要的方式实现。我建议将中间件与路由器组中间件选项一起使用。


删除全局中间件注册

/bootstrap/app.php

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

将两个中间件添加到路由中间件

/bootstrap/app.php

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

创建两个路由组:一个只包含auth.token.authenticate一个组,一个包含两个auth.token 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
}]);

我认为这是获得预期效果的最干净的方法。


推荐阅读