如何覆盖组中间件?我想要实现的是为注册/登录路由添加其他限制。
我当前的油门是在内核中设置的。
'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
据我所知,我的新中间件尚未应用。但我的节流请求被计算了两次。我如何应用不同的中间件来限制登录/注册路由并覆盖旧的?
老话题,但这是我发现的第一个;是时候更新答案了。
我过去也遇到过这个问题。当时我的解决方案是在控制器的构造函数中添加中间件。我不喜欢它,但它有效。
我目前正在一个新项目中使用 Laravel 8,发现以下解决方案有效:
kernel.php
'api' => [
'throttle:40,1',
'bindings',
],
throttle:40,1
,并添加正确的中间件throttle:15,3
:Route::post('login', 'Api\UserController@login')->withoutMiddleware('throttle:40,1')->middleware('throttle:15,3')->name('user.login');
如果不删除中间件,它将每个请求运行两次节流中间件。
我还在
$this->middleware( 'throttle:40,1' )->except( ['login'] )
的构造函数中使用了 Api\UserController
,但这并没有给出所需的结果;它只会为除一种方法之外的所有方法添加中间件,它不会覆盖。
有同样的问题,只是做了一些研究。似乎没有办法覆盖中间件配置。
我也看到我的中间件已在
route:list
中更新,但是在解析中间件时,它始终使用一组合并的规则,因此初始 api
规则最终将覆盖任何定义其他内容的规则。
您有几个选择:
从内核
api
中间件定义中删除限制规则,然后使用 Route::group()
将该特定规则重新添加到其余路由中。然后,在同一个文件中,您可以创建一个新的 Route::group()
来定义自定义油门配置。
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'));
}
据我所知,覆盖组中间件的唯一方法是禁用它,然后启用另一个:
Route::withoutMiddleware(ThrottleRequests::class.':api')->group(function () {
Route::middleware(ThrottleRequests::class.':custom')->group(function () {
///
});
});
让我知道是否有更好的方法。我想清理这个。