【问题标题】:Laravel override group middlewareLaravel 覆盖组中间件
【发布时间】:2019-10-16 15:18:43
【问题描述】:

如何覆盖组中间件?我想要实现的是为注册/登录路由添加其他油门限制。

我当前的油门是在内核中设置的。

'api' => [
        'throttle:40,1',
        'bindings',
    ],

我想为登录/注册路由设置新的油门限制。

我就是这样做的。

Route::post('login', 'Api\UserController@login')->middleware('throttle:15,3')->name('user.login');
Route::post('register', 'Api\UserController@register')->middleware('throttle:15,3')->name('user.register');

当我运行 php artisan route:list 时,它说这个中间件 api,throttle:15,3 应用于这个路由。

问题是当我运行登录请求时,响应头说

X-RateLimit-Limit       40
X-RateLimit-Remaining   38

据我所知,我的新中间件未应用。但是我的油门请求被计算了两次。如何在登录/注册路由上应用不同的中间件来限制并覆盖旧的?

【问题讨论】:

    标签: php laravel throttling


    【解决方案1】:

    有同样的问题,只是做了一些研究。似乎没有办法覆盖中间件配置。

    我也看到我的中间件已在 route:list 中更新,但在解析中间件时,它总是使用一组合并的规则,因此最初的 api 规则最终会覆盖任何定义其他内容的内容.

    你有几个选择:

    1. 从内核api 中间件定义中删除限制规则,然后使用Route::group() 将该特定规则重新添加到其余路由中。然后,在同一个文件中,您可以创建一个新的Route::group(),它定义了自定义油门配置。

      Route::group(['middleware' => 'throttle:120,1'], function () {
           ...
      });
      
      Route::group(['middleware' => 'throttle:15,3'], function () {
           ...
      });
      
    2. 创建一个自定义api-auth.php 文件,该文件包含在您定义的自定义中间件组中,就像默认的api 中间件一样。 (您需要在 RouteServiceProvider 中添加另一个调用以像这样加载它:

      public function map() { 
          ...
          $this->mapCustomAuthRoutes();
      }
      
      protected function mapCustomAuthRoutes()
      {
          Route::middleware(['throttle:15,3', 'bindings'])
              ->namespace($this->namespace)
              ->as('api.')
              ->group(base_path('routes/api-auth.php'));
      }
      

    【讨论】:

      【解决方案2】:

      老话题,但它是我发现的第一个;是时候更新答案了。

      我过去也遇到过这个问题。我当时的解决方案是在控制器的构造函数中添加中间件。我不喜欢它,但它有效。

      我目前在一个新项目中使用 Laravel 8,发现以下解决方案有效:

      1. kernel.php中设置默认中间件
      'api' => [
              'throttle:40,1',
              'bindings',
          ],
      
      1. 从具体路由中移除中间件throttle:40,1,并添加正确的中间件throttle:15,3
      Route::post('login', 'Api\UserController@login')->withoutMiddleware('throttle:40,1')->middleware('throttle:15,3')->name('user.login');
      

      如果您不删除中间件,它将在每个请求中运行两次油门中间件。

      我还在Api\UserController 的构造函数中使用了$this->middleware( 'throttle:40,1' )->except( ['login'] ),但这并没有给出所需的结果;它只会为除一种方法之外的所有方法添加中间件,它不会覆盖。

      【讨论】:

        猜你喜欢
        • 2016-10-09
        • 2019-02-22
        • 2022-01-25
        • 2016-10-14
        • 2021-09-23
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多