LARAVEL - Customize response headers when using rate limiting middleware

Viewed 723

I am developing a project in laravel8 (which is still new) and I want to hide some custom response headers(starting with x-) like:

X-RateLimit-Limit: 15
X-RateLimit-Remaining: 14

enter image description here

I want to customize this behavior and hide these headers, how can I easily find code (in a framework), which set's these headers

My code:


    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(15);
        });
    }
1 Answers

Let's say we can create a new App\Http\Middleware\ThrottleRequests class which will extend original \Illuminate\Routing\Middleware\ThrottleRequests. And override the method getHeaders to your own that will return empty array.

namespace App\Http\Middleware;

use Illuminate\Routing\Middleware\ThrottleRequests as OriginalThrottleRequests;

/**
...
 */
class ThrottleRequests extends OriginalThrottleRequests
{
    /**
     * @inheritdoc
     */
    protected function getHeaders($maxAttempts, $remainingAttempts, $retryAfter = null)
    {
        return [];
    }
}

And then all you need to do is to change middleware definitions inside app/Http/Kernel.php file. Property $routeMiddleware where you register 'throttle' middleware \Illuminate\Routing\Middleware\ThrottleRequests::class you can change to your own implementation \App\Http\Middleware\ThrottleRequests::class.

In my case it is:

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        //...
        'throttle' => \App\Http\Middleware\ThrottleRequests::class,
        //...
    ];
Related