DEV3 Technologies home

DEV3 Developer Forum

How do I add rate limiting to login and API routes in Laravel 12?

Laravel helpSolved0 views
dev3 ·

I want to stop brute force login attempts and limit my API to 60 requests per minute per user, with a stricter limit for a heavy export endpoint. How do I define and apply rate limiters in Laravel 12?

#laravel#security#rate-limiting

0

1 reply

dev3 · Accepted answer

Define named limiters in AppServiceProvider::boot() using RateLimiter::for, then attach them with the throttle middleware.

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('exports', function (Request $request) {
        return [
            Limit::perMinute(2)->by($request->user()->id),
            Limit::perDay(20)->by($request->user()->id),
        ];
    });

    RateLimiter::for('login', function (Request $request) {
        $key = strtolower($request->input('email')).'|'.$request->ip();
        return Limit::perMinute(5)->by($key);
    });
}

Apply on routes:

Route::middleware('throttle:login')->post('/login', LoginController::class);
Route::middleware(['auth:sanctum', 'throttle:exports'])->get('/export', ExportController::class);

For API routes the default group applies throttle:api once you enable it in bootstrap/app.php with $middleware->throttleApi().

Custom response

Limit::perMinute(5)->by($key)->response(fn () => response()->json(['message' => 'Slow down'], 429));

Pitfalls

  • Limits are stored in the cache. The array driver never limits across requests; use redis, database or file. For Redis there is $middleware->throttleWithRedis().
  • Behind a proxy or Cloudflare all users share the proxy IP unless you trust proxies, so everybody gets blocked together.
  • Clients should read the Retry-After and X-RateLimit-Remaining headers.
  • Rate limit by email plus IP on login, not IP alone, so attackers cannot rotate IPs against one account.

The DEV3 snippet on token rate limits shows this with Sanctum abilities.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.