【问题标题】:Laravel 8 rate limiter not working for routesLaravel 8速率限制器不适用于路线
【发布时间】:2021-04-01 00:14:18
【问题描述】:

在 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 响应。

如何解决这个问题?

谢谢

【问题讨论】:

  • 您是否尝试过配置您的限速here
  • 您可能需要在configureRateLimiting() 函数的App\Providers\RouteServiceProvider 中包含一个速率限制器。
  • 是的,尝试在 RouteServiceProvider.php 中添加 RateLimiter::for('requestslimit', function (Request $request) {return Limit::perMinute(3);}); 并在路由中添加 middleware('throttle:requestslimit')
  • 嗯,如果你的项目中安装了限速中间件,你也许可以看到它是否被应用在了望远镜中。

标签: php laravel throttling laravel-8 rate-limiting


【解决方案1】:

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 更新,不要忘记在 RouteServiceProviderboot() 方法中添加对方法的调用。否则将不会应用限制。

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

【讨论】:

  • laracasts 视频对我很有帮助。谢谢。
【解决方案2】:

转到.env文件并检查您的缓存驱动程序如果CACHE_DRIVER=none,请设置缓存驱动程序。
Laravel 支持 支持:“apc”、“array”、“database”、“file”、 “memcached”、“redis”、“dynamodb”

【讨论】:

    【解决方案3】:

    我有问题。在 config/cache.php 中,默认设置为“null”。我改为“数据库”。现在,这工作正常。

    【讨论】:

      【解决方案4】:

      在 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);
                  }
      
              });
          }
      
      

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2022-10-14
        • 1970-01-01
        • 2017-08-20
        • 2022-01-07
        • 2021-10-31
        • 1970-01-01
        • 2020-05-16
        • 2021-07-09
        相关资源
        最近更新 更多