简体   繁体   中英

Laravel Throttling in Controller Class

I am trying to implement throttling on my Laravel 8 application. I have added the configureRateLimiting() method to the RouteServiceProvider.php file to limit unauthenticated requests to 20 per minute per IP address, as follows:

protected function configureRateLimiting() {
  Log::info( "Configuring..." );
  RateLimiter::for( 'global', function (Request $request) {
    Log::info( "Testing...");
    return $request->user()
      ? Limit::none()
      : Limit::perMinute(20)->by($request->ip());
  });
}

And I have added a constructor to my Controller.php file:

public function __construct() {
  $this->middleware('throttle:global');
}

I have not modified my Kernel.php file. The ThrottleRequests class is listed in the web middlewareGroup :

protected $middlewareGroups = [
  'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ],
...

My problem is that the configureRateLimiting() method is not getting called. The "Configuring..." message never shows in the log (neither does the "Testing..." message). Rate limiting is in effect, but it is always triggered, so I always see the 429 page, even immediately after running php artisan cache:clear .

Interestingly, If I change the Controller constructor to:

public function __construct() {
  Log::info( "In constructor." );
  $this->middleware('throttle:10,1');
}

I get throttled after 5 requests. And if I change the parameter to throttle:20,1 , I get throttled after 10 requests. I always seem to get throttled after half the required number, even though the "In constructor." messaged is only logged once per request.

What have I missed? How do I get the global throttle working?

The problem is that my RouteServiceProvider.php file had not been updated from Laravel 7, so the boot() method was not calling configureRateLimiting() . Once I switched it out for the Laravel 8 version, and added my custom code, everything started working as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM