Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Testing and Hardening

Login Throttling and Rate Limiting

Stop password guessing and credential stuffing: failed-attempt counters, account lockout trade-offs, per-IP limits, token buckets, uniform error messages and a runnable stand-in.

A login form is a guessing machine that you host for attackers. Without limits, a script can try thousands of passwords per minute against one account (brute force) or one leaked password against thousands of accounts (credential stuffing). Strong password hashing makes each guess cost more on your server too, so you also need to make sure guesses are rare.

Spring Security does not ship a rate limiter, but it gives you every hook you need: authentication events, AuthenticationFailureHandler, UserDetails.isAccountNonLocked(), and filters. The framework classes cannot run on this site, so the runnable examples below are plain Java stand-ins for the algorithms; the Spring wiring is shown read-only.

Three layers of defence

Layer What it limits Typical rule
Per account Guesses against one username Delay or lock after 5 to 10 failures
Per client (IP or device) One source trying many usernames 20 attempts per minute per IP
Global A distributed attack Alerts, CAPTCHA, extra verification

Use more than one layer. Only counting per account lets an attacker lock out real users on purpose (a denial of service). Only counting per IP fails against botnets and shared office addresses.

Slow the guesser, not the user

Count Failures per account and IP
Delay Back off, then lock briefly
Alert Log and notify on spikes

Short, automatic locks beat permanent ones

1 / 2

A failure counter with a time window

The simplest useful control remembers recent failures per key and refuses further attempts for a short time once a threshold is reached. Success clears the counter. The key can be a username, an IP, or both.

Java Lock after repeated failures (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the correct password is refused while the account is locked. That is deliberate: if a locked account still accepted the right password, an attacker could keep guessing and simply watch for the one success.

Token bucket: a smooth per-client limit

A token bucket allows short bursts but enforces an average rate. The bucket holds up to capacity tokens and refills at a fixed speed; each request spends one token, and an empty bucket means rejection. This is what most rate-limit libraries implement, and it fits per-IP limits well.

Java A token bucket per client (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Wiring it into Spring Security (read-only)

Spring publishes an event for every authentication result. A listener can feed your counters without touching the filter chain:

Java
@Component
class LoginAttemptListener {

    private final LoginAttemptService attempts;

    LoginAttemptListener(LoginAttemptService attempts) {
        this.attempts = attempts;
    }

    @EventListener
    void onFailure(AbstractAuthenticationFailureEvent event) {
        attempts.recordFailure(event.getAuthentication().getName());
    }

    @EventListener
    void onSuccess(AuthenticationSuccessEvent event) {
        attempts.reset(event.getAuthentication().getName());
    }
}

To refuse locked users, report it from UserDetails. DaoAuthenticationProvider checks isAccountNonLocked() before comparing the password and throws LockedException:

Java
UserDetails user = User.withUsername(name)
    .password(hash)
    .roles("USER")
    .accountLocked(attempts.isLocked(name))
    .build();

For per-IP limits, a servlet filter registered before the login filter is the usual place. Return 429 Too Many Requests with a Retry-After header and stop the chain:

Java
http.addFilterBefore(new RateLimitFilter(), UsernamePasswordAuthenticationFilter.class);

Behind a reverse proxy, request.getRemoteAddr() is the proxy's address. Configure server.forward-headers-strategy so the real client address is used, and never trust X-Forwarded-For from the open internet.

Uniform answers and timing

If "unknown user" returns a different message, status or response time than "wrong password", attackers can harvest valid usernames. Spring's DaoAuthenticationProvider already hides the difference by default (hideUserNotFoundExceptions is true) and runs a dummy password hash for missing users to even out timing. Keep your own messages equally vague, for example "Invalid username or password", and apply the same rule to password reset and sign-up pages.

In a cluster, in-memory counters are per server. Store counters in Redis or the database (or use a gateway or CDN rate limit) so an attacker cannot multiply their budget by the number of nodes.

Beyond counters

  • CAPTCHA or proof of work after a few failures raises the cost of automation.
  • Multi-factor authentication makes a guessed password useless on its own.
  • Breached-password checks on sign-up and change stop reuse of leaked credentials.
  • Alerting on a sudden jump in failures catches credential stuffing early; see audit events and logging.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a permanent lockout after N failures a risky default?

    Short, automatic locks and per-client limits protect accounts without handing attackers a way to disable them.
  2. 2. What does a token bucket allow that a fixed 'one per interval' rule does not?

    The bucket stores unused capacity, so a client can burst up to the capacity and is then held to the refill rate.
  3. 3. Which Spring hook lets you count failed logins without changing the filter chain?

    Spring publishes authentication success and failure events that any bean can listen to.
  4. 4. Why should unknown-user and wrong-password responses look identical?

    Different messages or timings leak account existence, which fuels targeted guessing and phishing.

Summary

  • Limit guesses per account and per client; use both, plus alerting.
  • Prefer short automatic locks and back-off over permanent lockouts.
  • A token bucket gives burst tolerance with a steady average rate.
  • In Spring, use authentication events, isAccountNonLocked() and a filter before the login filter.
  • Keep messages and timing identical for unknown users and bad passwords, and keep counters in shared storage in a cluster.

Next: Security audit events and logging