设置中间件优先级App\Http\Kernel
例如,在这里我需要我的自定义身份验证中间件首先运行(在替换绑定之前),所以我将它移到堆栈上:
public function __construct(Application $app, Router $router)
{
/**
* Because we are using a custom authentication middleware,
* we want to ensure it's executed early in the stack.
*/
array_unshift($this->middlewarePriority, MyCustomApiAuthMiddleware::class);
parent::__construct($app, $router);
}
或者,如果您需要显式控制,您可以覆盖整个优先级结构(不推荐,因为您必须在升级期间密切注意以查看框架是否更改)。特定于这个问题的是SubstituteBindings
处理路由模型绑定的类,因此只需确保您的身份验证中间件在此之前的某个时间出现。
/**
* The priority-sorted list of middleware.
*
* Forces the listed middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\App\Http\Middleware\MyCustomApiAuthMiddleware::class
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];