php - Laravel 覆盖组中间件

标签 php laravel throttling

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

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

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

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

我就是这样做的。
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

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

最佳答案

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

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

你有几个选择:

  • 从内核中删除 throttle 规则 api中间件定义然后使用 Route::group()将该特定规则重新添加到其余路由中。然后,在同一个文件中,您可以创建一个新的 Route::group()它定义了自定义 throttle 配置。
    Route::group(['middleware' => 'throttle:120,1'], function () {
         ...
    });
    
    Route::group(['middleware' => 'throttle:15,3'], function () {
         ...
    });
    
  • 创建自定义 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'));
    }
    
  • 关于php - Laravel 覆盖组中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56387199/

    相关文章:

    microsoft-graph-sdks - 使用 Microsoft Graph SDK C# 5.2x 处理限制错误

    ruby-on-rails - 限制向用户发送大量消息的 "rails way"是什么?

    php - 在不同命名空间之间转换异常

    php - 如何访问 Twig 中的动态变量名?

    php - 401 重定向神奇地导致 302 重定向

    mysql - NULL 值保存在数据库中而不是用户提交的信息

    javascript - 如何获取每次迭代的值?

    javascript - 在 Woocommerce 可变产品的 jQuery 中获取选定的变化价格

    php - PHP MYSQL 如何自动向另一个表添加新行

    javascript - Throttle-debounce 的事件对象