Laravel Api route protect RateLimit
// Need to add this code in , RouteServiceProvider.php file
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Cache\RateLimiting\Limit;
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
1. configureRateLimiting() method:
This method is responsible for defining the rate-limiting rules for
different routes (in this case, for the API routes).
It uses Laravel's RateLimiter facade to define how many requests
can be made by a user or client in a certain period of time.
2. RateLimiter::for('api', function (Request $request) {...}):
This code is registering a rate limit for the "api" route group
using the RateLimiter::for() method. It takes two arguments:
The first argument ('api') specifies the name of the rate-limiting
configuration, typically for the API routes.
The second argument is a callback function that takes the Request
object and defines the limit behavior.
3. Limit::perMinute(60):
This part sets the rate limit. It allows 60 requests per minute
for the "api" route group. You can adjust this value to control
how many requests a user is allowed to make within a minute.
4. by($request->user()?->id ?: $request->ip()):
This part determines how the rate limit is applied:
$request->user()?->id: This attempts to get the authenticated
user's ID. The ?-> (null-safe operator) is used to avoid errors
if the user is not authenticated (i.e., if there is no user,
it returns null).
?: $request->ip(): If no user is authenticated (i.e., for guest users),
the rate limit is applied based on the IP address of the request.
This ensures that even anonymous users are subject to rate limiting.
How the Logic Works:
If the request is made by an authenticated user, the rate limit is
applied based on the user ID.
If the request is made by an unauthenticated user (guest), the rate
limit is applied based on the IP address of the client.
This means:
Authenticated users can make 60 requests per minute based on their
user ID.
Unauthenticated (guest) users can make 60 requests per minute based
on their IP address.
Purpose:
Rate limiting is important to:
Prevent abuse by limiting how many requests a user or client can make
within a specific time.
Protect the application from DDoS attacks or from being overwhelmed
by excessive requests.
Ensure that API resources are fairly distributed across users.
No comments