Home » Php » php – Throttling protection when multiple users have the same IP address

php – Throttling protection when multiple users have the same IP address

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am using Laravel to provide access to an API for an internal Mobile App.
But the service is hosted outside of our enterprise network, while users are connected to internet through the same router (which is the enterprise network).

In order to prevent spam of routes like “Send email again“, I created my own middleware that I can apply only on the routes I want (throttling).

The code looks like this :

class ThrottleRoute
{
    protected $limiter;

    public function __construct(RateLimiter $limiter)
    {
        $this->limiter = $limiter;
    }

    public function handle($request, Closure $next, $max_attempts = 60, $decay_seconds = 60)
    {
        $key = $this->resolveRequestSignature($request);
        $attempts = $this->limiter->hit($key, $decay_seconds);

        if ($attempts > (int) $max_attempts) {
            return abort(429);
        }

        return $next($request);
    }

    private function resolveRequestSignature($request)
    {
        $route = $request->route();
        if (!$route) {
            throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
        }

        $route_part = $route->getDomain() . '|' . $route->uri;
        $user_part = ($user = $request->user()) ? $user->getAuthIdentifier() : $request->ip();
        return sha1("$route_part|$user_part");
    }
}

This is working nicely when mobile apps users are authenticated (because in this case it will use the AuthIdentifier as part of the unique key).
But, when people are not authenticated, I have some routes I want to protect too, and in this case I am using the IP address. The problem is, we are many with the same IP address and 429 errors are fired really quickly because of it even if a user never performed a request yet (maybe something like 100-500 users using the app in the same time, on the same network).

I am looking for a solution to better identity each user when not connected and using the same external IP address.

How to&Answers: