Rate Limiting for Authentication — Auth

Login is limited before the password is checked, with two counting keys (tags that identify the sender): email|IP with a strict limit (5 per 60 seconds in the…

How many times a minute may the School Portal login form be tried? If the answer is "no limit", one script can keep trying Siti's password without ever stopping.

Rate limiting for authentication puts a limit on how many times the login form may be tried in a span of time. The attempts are counted per key, the counting key (a tag that identifies the sender): per account from one IP, and per IP. Once the limit is exceeded, the server refuses with 429 without checking the password at all. Picture the guard at the school gate. A visitor who gets a teacher's name wrong may try again, but after five tries in a minute, they are asked to wait at the guard post. Everyone on one bus also shares one allowance of tries. A visitor who got it wrong three times has to show an ID card first. In this picture, the guard is the server, each visitor is one account being tried, and a wrong name is a wrong password. Waiting at the post is the 429 answer, one bus is one IP, and the ID card is the captcha.

Why login needs a limit of its own

Login is the main endpoint that takes password guesses. Every attempt is also expensive for the server: password hashing is slow on purpose (the Password Hashing lesson), so a thousand attempts a minute means a thousand slow hashes a minute. That is why the limit sits before the password is checked, and is far stricter than on other endpoints. The Account Recovery & Lockout lesson holds back an email|IP pair after 5 wrong passwords. This lesson adds a limit on every attempt, right or wrong, per email|IP and per IP, and a captcha per account. The attack side, brute force and credential stuffing (trying email and password pairs leaked from other sites), is covered in the Rate Limiting & Throttling lesson of the Security track. Here we build the limit for School Portal.

Two keys: per account and per IP

Counting key Limit in the Lab What it holds back
email|IP, for example [email protected]|198.51.100.23 5 per 60 seconds one account tried over and over from one IP
IP, for example 198.51.100.23 10 per 60 seconds one IP trying many accounts
the account alone, [email protected] a captcha after 3 failures within 15 minutes one account tried from many IPs

A sliding window on every attempt

This is the rate limiter, with a sliding window that records every attempt:

function createRateLimiter(windowMs, maxRequests) {
  const hits = new Map(); // key -> [attempt time, ...]
  return function allow(key, now) {
    const recent = (hits.get(key) || []).filter((t) => t > now - windowMs); // the moving window
    recent.push(now); // recorded, even if it is refused
    hits.set(key, recent);
    return recent.length <= maxRequests;
  };
}

const perEmailIp = createRateLimiter(60 * 1000, 5);
const perIp = createRateLimiter(60 * 1000, 10);

allow(key, now) answers true (passes) or false (refused) for one counting key.

School Portal's limit is 5 attempts per 60 seconds per email|IP. From an internet cafe, Siti sends a login every 2 seconds starting at 07:00:00. Her first six attempts all fail or are refused. Before you look at the trace, guess: what does the sixth attempt, at 07:00:10, get back, and what is its Retry-After?

Here is a trace from the Lab, all from the internet cafe at 198.51.100.23:

Time Attempt email|IP in 60 seconds Account failures Answer
07:00:00 Siti, wrong password 1 1 401
07:00:02 Siti, wrong password 2 2 401
07:00:04 Siti, wrong password 3 3 401, "captcha_required": true
07:00:06 Siti, wrong, no captcha 4 3 422, password not checked
07:00:08 Siti, wrong, with captcha 5 4 401
07:00:10 Siti, right password 6 4 429, Retry-After: 52
07:01:02 Siti, right, with captcha 5 0 200

The sixth attempt gets 429 Too Many Requests with Retry-After: 52, even though the password is right. Why 52? The window holds six records: seconds 0, 2, 4, 6, 8 and 10, including the refused one at second 10. The next attempt is recorded too, so for it to pass, at most four old records may remain: the records at seconds 0 and 2 have to leave. The record at second 2 leaves at second 62, and 62 minus 10 is 52.

In the exercise, the result of createRateLimiter(60000, 3) (3 attempts per 60 seconds) is stored in limit. This limit function is called with the counting keys 'ip1' and 'ip2', and time is a number of milliseconds. Different counting keys keep their own records. Because refused attempts are recorded too, limit('ip1', 62500) is still false: the records at 3000, 4000 (the refused one) and 62000 are still in the window.

The 429 answer and Retry-After

This is the server's answer to Siti's sixth attempt. X-RateLimit-Limit is the limit, and X-RateLimit-Remaining the attempts left:

HTTP/1.1 429 Too Many Requests
Retry-After: 52
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 0
Content-Type: application/json

{"message": "Too Many Attempts."}

A captcha after 3 failures

Failures per account are counted with a 15-minute sliding window, as in the Account Recovery & Lockout lesson. But here the counting key is the email alone, without the IP. Once there are 3 failures, the 401 answer carries "captcha_required": true, and the form shows a captcha. The next attempt without a captcha gets 422 before the password is checked. The captcha step follows the account, so switching IPs doesn't remove it. Siti herself can still log in: she just fills in the captcha. A successful login clears the failure count.

handleLogin below puts it all together. recordFailure, recentFailures and clearFailures handle the failures per account, and checkPassword checks the password:

function handleLogin({ email, password, captcha }, ip, now) {
  const okEmailIp = perEmailIp(`${email}|${ip}`, now); // both are always called,
  const okIp = perIp(ip, now);                         // so both record the attempt
  if (!okEmailIp || !okIp) return { status: 429 };
  if (recentFailures(email, now) >= 3 && !captcha) return { status: 422, captcha_required: true };
  if (!checkPassword(email, password)) {
    recordFailure(email, now);
    return { status: 401, captcha_required: recentFailures(email, now) >= 3 };
  }
  clearFailures(email);
  return { status: 200 };
}

In Laravel

In Laravel, the two limits become one named rule:

// app/Providers/AppServiceProvider.php, in the boot() method
RateLimiter::for('login', function (Request $request) {
    $email = Str::lower((string) $request->input('email'));

    return [
        Limit::perMinute(5)->by('email-ip:'.$email.'|'.$request->ip()),
        Limit::perMinute(10)->by('ip:'.$request->ip()),
    ];
});

// routes/web.php
Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:login');

// LoginController@store, before Auth::attempt: a captcha after 3 account failures
$failures = 'login-failures:'.Str::lower($request->input('email'));
if (RateLimiter::attempts($failures) >= 3) {
    $captcha = Http::asForm()->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
        'secret' => config('services.turnstile.secret'),
        'response' => $request->input('cf-turnstile-response'),
        'remoteip' => $request->ip(),
    ]);
    if (! $captcha->json('success')) {
        return response()->json(['message' => 'Complete the captcha first.', 'captcha_required' => true], 422);
    }
}

⚠️ Limits that stop the wrong people, or come too late

TL;DR: Login is limited before the password is checked, with two counting keys (tags that identify the sender): email|IP with a strict limit (5 per 60 seconds in the Lab) and the IP with a loose one (10 per 60 seconds). A limit per IP alone isn't enough: one person can switch IPs, and many legitimate users share one public IP behind NAT. The count is a sliding window: only the attempts of the last 60 seconds count, one made exactly 60 seconds ago no longer counts, and refused ones are recorded too. Once the limit is exceeded: 429 Too Many Requests with Retry-After (how long to wait). An account isn't blocked: it is asked for a captcha after 3 failures within 15 minutes. In Laravel: RateLimiter::for('login') holding several Limit::perMinute(...)->by(...), attached with throttle:login, plus RateLimiter::attempts, hit and clear for the captcha.

⚡ Login needs a limit of its own

Meaning: With no limit, one script can keep trying Siti's password without ever stopping. Every attempt is also expensive for the server, because password hashing is slow on purpose. That is why the limit is checked before the password.

⚡ Per IP alone isn't enough

Meaning: An attacker can switch IPs through a botnet (many devices they control), a proxy (a go-between server) or a VPN (a service that sends the connection through another server). On the other hand, many legitimate users share one IP: 30 students in the school's computer lab reach the internet through one public IP (NAT). So the per-IP limit is loose. The strict limit is counted per email|IP, that is, one email from one IP. Per account, the server doesn't block: it asks for a captcha after 3 failures.

⚡ A sliding window on every attempt

Write:

function createRateLimiter(windowMs, maxRequests) {
  const hits = new Map(); // key -> [attempt time, ...]
  return function allow(key, now) {
    const recent = (hits.get(key) || []).filter((t) => t > now - windowMs); // the moving window
    recent.push(now); // recorded, even if it is refused
    hits.set(key, recent);
    return recent.length <= maxRequests;
  };
}
Guess first: this limiter is used with a limit of 5 attempts per 60 seconds. Siti tries to log in every 2 seconds, and her sixth attempt (10 seconds after the first) has the right password. What does it get back?

429 Too Many Requests with Retry-After: 52, even though the password is right. The window holds six records (seconds 0 to 10). The next attempt is also recorded, so for it to pass (5 records at most), the two oldest records (seconds 0 and 2) have to leave first. The record at second 2 leaves at second 62, and 62 minus 10 is 52. Refused attempts are recorded too, so a client that keeps sending without waiting stays held back.

What you will learn