## 中间件 三大步骤 1声明 2注册 3使用 **1 声明** 执行命令创建中间件 ``` php artisan make:middleware CheckAuth ``` ~~~ public function handle(Request $request, Closure $next) { $filter_api = [ //过滤掉几个别特殊的API(不做请求验证) ]; if(!in_array($request->route()->uri,$filter_api)){ $result = Manage::checkUserAuth($request->login_id,$request->method(),$request->route()->uri); if(!$result) return response(errorMsg(-1,"权限验证失败 请联系管理人员!!!")); } return $next($request); } ~~~ **2注册 在 middleware/kernel.php $routeMiddleware数组中添加** ~~~ 'CheckAuthority' => \App\Http\Middleware\CheckAuthority::class, ~~~ **3使用** 在路由中 ~~~ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); ~~~ 在 Provides/RouteServiceProvider.php中 ~~~ Route::prefix('api') ->middleware(['api','CheckAuthority']) ->namespace($this->namespace) ~~~ 添加中间件 执行顺序 在 http/Kernel.php 中添加以下代码 ~~~ // 中间件执行顺序 protected $middlewarePriority = [ CheckToken::class, CheckAuthority::class, AddLog::class, ]; ~~~