[英]Laravel 8 rate limiter not working for routes
在 web.php 路线中,我有以下内容:
Route::middleware('throttle:3,1')->group(function () {
Route::get('/about', function () {
return "About Info";
});
});
Laravel 框架是 8.19.0。
理想情况下,当有人在 1 分钟内点击页面超过 3 次时,laravel 应该给出 429 Too Many Attempts 响应。 但事实并非如此。 3 次后我没有收到 429 响应。
如何解决这个问题?
谢谢
从Laravel 8 开始,您可以在App\Providers\RouteServiceProvider
的configureRateLimiting()
方法中配置速率限制。
例如:
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
如果您已从 Laravel 7 更新,请不要忘记在RouteServiceProvider
的boot()
方法中添加对该方法的调用。 否则限制将不适用。
public function boot()
{
$this->configureRateLimiting();
parent::boot();
}
另请参阅文档: https://laravel.com/docs/8.x/routing#rate-limiting和 Laracasts 视频: https://laracasts.com/series/whats-new-in-laravel-8/episodes/9
go 到.env
文件并检查您的缓存驱动程序如果CACHE_DRIVER=none
,设置缓存驱动程序。
Laravel 支持支持:“apc”、“array”、“database”、“file”、“memcached”、“redis”、“dynamodb”
我有这个问题。 在 config/cache.php 中,默认设置为“null”。 我改为“数据库”。 现在,这工作正常。
在 laravel 8 我以这种方式实现了这个,它易于使用:
在RouteServiceProvider.php
中添加:
use Illuminate\Http\Response;
use Illuminate\Support\Facades\RateLimiter;
protected function configureRateLimiting()
{
RateLimiter::for('login', function (Request $request) {
$key = 'login.' . $request->input('username') . '.' . $request->ip();
$max = 5; //attempts
$decay = 120; // 120 seconds/2 minute for suspending
if (RateLimiter::tooManyAttempts($key, $max)) {
return response()->json(['message' => __("messages.login.throttle.suspension")], Response::HTTP_UNPROCESSABLE_ENTITY);
} else {
RateLimiter::hit($key, $decay);
}
});
}
出现问题是因为替换了Laravel当前版本不对应的provider文件,解决方法是上传到服务器时压缩整个工程文件夹,如果问题出在本地电脑,恢复工程全新安装
方法一
app/Http/Providers/RouteServiceProvider.php
默认的configureRateLimiting()
方法已经存在。
方法二
routes/api.php
Route::post('/send-otp', 'UtilityController@sendOtp')->middleware(['throttle:5,1']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.