I have an API that is using Laravel that is being called from another instance of Laravel with Guzzle.
The second server's IP address is triggering the throttle on the API.
I would like to pass through the user's domain and IP address from the second server to the API. I am hoping not to recode the Throttle middleware.
I am wondering if anyone has faced this before and if so how they solved it.
The middleware group on the API is set up like this
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'api' => [
'throttle:60,1',
\Barryvdh\Cors\HandleCors::class,
'bindings',
],
];
/**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
* @return string
*
* @throws \RuntimeException
*/
protected function resolveRequestSignature($request)
{
if ($user = $request->user()) {
return sha1($user->getAuthIdentifier());
}
if ($route = $request->route()) {
return sha1($route->getDomain().'|'.$request->ip());
}
throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
}
You can pass the client's IP address with the X_FORWARDED_FOR
header, that way the IP address of the second server is not blocked.
Route::get('/', function (Request $request) {
$client = new \GuzzleHttp\Client();
$request = $client->request('GET', '/api/example', [
'headers' => ['X_FORWARDED_FOR' => $request->ip()]
]);
$response = $request->getBody();
});
On your main server you need to add your second server as a trusted proxy (docs) to App\Http\Middleware\TrustProxies
in order to take the IP from this header.
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array
*/
protected $proxies = [
'192.168.1.1', // <-- set the ip of the second server here
];
//...
}
Now every call to $request->ip()
on the main server will have the original client IP instead of the second server's IP. That will also affect the throttling.