Mil*_*ita 6 php throttling laravel
如何覆盖组中间件?我想要实现的是为注册/登录路由添加其他节流限制。
我当前的油门是在内核中设置的。
'api' => [
'throttle:40,1',
'bindings',
],
Run Code Online (Sandbox Code Playgroud)
我想为登录/注册路由设置新的节流限制。
我就是这样做的。
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');
Run Code Online (Sandbox Code Playgroud)
当我运行 php artisan route:list 时,它说这个中间件 api,throttle:15,3 应用于这条路线。
问题是当我运行登录请求时,响应头说
X-RateLimit-Limit 40
X-RateLimit-Remaining 38
Run Code Online (Sandbox Code Playgroud)
所以据我所知,我的新中间件没有被应用。但是我的油门请求被计算了两次。我如何应用不同的中间件来限制登录/注册路由并覆盖旧的?
老话题,但这是我发现的第一个;是时候更新答案了。
我过去也遇到过这个问题。当时我的解决方案是在控制器的构造函数中添加中间件。我不喜欢它,但它有效。
我目前正在一个新项目中使用 Laravel 8,发现以下解决方案有效:
kernel.php
'api' => [
'throttle:40,1',
'bindings',
],
Run Code Online (Sandbox Code Playgroud)
throttle:40,1
从特定路由中删除中间件,并添加正确的中间件throttle:15,3
:Route::post('login', 'Api\UserController@login')->withoutMiddleware('throttle:40,1')->middleware('throttle:15,3')->name('user.login');
Run Code Online (Sandbox Code Playgroud)
如果您不删除中间件,它将每个请求运行两次节流中间件。
$this->middleware( 'throttle:40,1' )->except( ['login'] )
我也在的构造函数中进行了尝试Api\UserController
,但是这并没有给出所需的结果;它只会为除一种方法之外的所有方法添加中间件,它不会覆盖。
有同样的问题,只是做了一些研究。似乎没有办法覆盖中间件配置。
我也看到我的中间件已经更新,route:list
但是在解析中间件时,它总是使用一组合并的规则,因此初始api
规则最终将覆盖任何定义其他内容的规则。
您有几个选择:
从内核中间件定义中删除限制规则api
,然后使用 aRoute::group()
将该特定规则重新添加到其余路由中。然后,在同一个文件中,您可以创建一个新文件Route::group()
来定义自定义节流配置。
Route::group(['middleware' => 'throttle:120,1'], function () {
...
});
Route::group(['middleware' => 'throttle:15,3'], function () {
...
});
Run Code Online (Sandbox Code Playgroud)创建一个自定义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'));
}
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
1763 次 |
最近记录: |