Laravel: Remove Request Throttling For Authenticated Users

3.3k views Asked by At

I wish to disable request throttling for users that are authenticated through the API.

Kernel:

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,
    ],

    'api' => [
        'throttle:240,1'
    ],
];

Throttle here will limit the requests to 240 per minute regardless of whether or not a user is authenticated.

How would it be possible to do this so it only throttles unauthenticated users?

2

There are 2 answers

0
Zoran Stankovic On

You could pack all auth routes to one group and set throttle to unlimited or in your controller class constructor you can disable ThrottleRequests middleware.

Please check this thread: Disable rate limiter in Laravel?

0
Altantur On

For the latest version of Laravel 8.x. We can use RateLimiter with the following steps:

  1. In your app/Providers/RouteServiceProvider.php find below configureRateLimiting:
    protected function configureRateLimiting()
    {

        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });

        // Add this for no limit throttle
        RateLimiter::for('none', function (Request $request) {
            return Limit::none();
        });

    }
  1. In your app/web.php add 'throttle:none':
Route::group([
  'middleware' => ['auth', 'throttle:none'],
  ], function ($router) {
    Route::post('test', 'TestController@test');
});
  1. This step is optional, If you are using other middleware you can group them up in your app/Http/Kernel.php:
    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,
        ],
        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'no_throttle' => [
            'throttle:none',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
Route::group([
  'middleware' => ['auth', 'no_throttle'],
  ], function ($router) {
    Route::post('test', 'TestController@test');
});