What is your Laravel version? And what HTTP client are you using?
Throwing ThrottleRequestsException but no Retry-After and X-RateLimit-Reset headers on response
I have a route with the Illuminate\Routing\Middleware\ThrottleRequests middleware as such:
$router->group(['middleware' => 'throttle:1,1'], function () use ($router) {
$router->get('/someresource', 'SomeResourceController@all');
});
And it is working as expected, when exceeding the limit of 1 request per minute (low limit set for testing purposes) the ThrottleRequestsException is thrown and a 429 Too many requests response returned but the Retry-After and X-RateLimit-Reset headers are absent from response headers
Example response
< HTTP/1.1 429 Too Many Requests
< Date: Fri, 30 Oct 2020 08:16:40 GMT
< Server: Apache/2.4.38 (Debian)
< Vary: Authorization
< X-Powered-By: PHP/7.4.11
< Cache-Control: no-cache, private
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
But the buildException method of class ThrottleRequests clearly sets them
protected function handleRequest($request, Closure $next, array $limits)
{
foreach ($limits as $limit) {
if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) {
dd($this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback)); //If I add this line I can see the headers
throw $this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback); //when exception is actually thrown the headers are missing from the http response
}
$this->limiter->hit($limit->key, $limit->decayMinutes * 60);
}
$response = $next($request);
foreach ($limits as $limit) {
$response = $this->addHeaders(
$response,
$limit->maxAttempts,
$this->calculateRemainingAttempts($limit->key, $limit->maxAttempts)
);
}
return $response;
}
dd() output of buildException()
^ Illuminate\Http\Exceptions\ThrottleRequestsException {#45 ▼
-statusCode: 429
-headers: array:4 [▼
"X-RateLimit-Limit" => 1
"X-RateLimit-Remaining" => 0
"Retry-After" => 57
"X-RateLimit-Reset" => 1604046100
]
#message: "Too Many Attempts."
#code: 0
#file: "/var/www/html/app/Http/Middleware/ThrottleRequests.php"
#line: 199
trace: {▶}
}
What I have tried to no avail:
- Disabling all other middleware I am running
- Different HTTP clients
- Different APP_ENV and APP_DEBUG value combinations
Try checking what it is getting here
https://github.com/laravel/lumen-framework/blob/8.x/src/Exceptions/Handler.php#L105
This response might not include the headers. You could add something like this to your own exception handler?
if ($e instanceof HttpResponseException) {
$response = $e->getResponse();
$response->headers->add($e->getHeaders()));
return $response;
}
Please or to participate in this conversation.