Brute-force login and account lockout
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A shop's login page answers every try, so a script can test thousands of passwords on one customer's account in minutes. How do you slow it down without locking real customers out?
Brute force and credential stuffing
Brute force is guessing a password by trying many values against the login endpoint, one after another. It only works when the endpoint answers as often as it is asked.
Two views of an unprotected login: the guessing time in numbers, then seven real wrong-password requests that all get an answer.
Example 1 · How long a guessing script needs, with and without a limit
public class GuessingMathDemo { public static void main(String[] args) { long commonPasswords = 10_000; // a list of the most used passwords long perSecond = 100; // a modest script against an open endpoint long secondsOpen = commonPasswords / perSecond; System.out.println("No limit: " + commonPasswords + " guesses in " + secondsOpen + " seconds");
long perWindow = 5; // ShopLite: 5 failures, then 15 minutes locked long windowMinutes = 15; long windows = commonPasswords / perWindow; long minutes = windows * windowMinutes; System.out.println("5 per 15 minutes: " + windows + " windows = " + minutes / 60 / 24 + " days"); }}No limit: 10000 guesses in 100 seconds 5 per 15 minutes: 2000 windows = 20 days
What this code does
- With no limit, ten thousand common passwords are tried in under two minutes.
- With five tries per fifteen minutes the same list takes about three weeks for one account, long enough for the owner and the security logs to notice.
- The numbers are a simple model: real attacks spread over many IPs, which is why ShopLite also limits per IP.
Example 2 · Mistake: a login endpoint with no limit
Runs in: the shoplite-api Spring Boot project
$ for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w "%{http_code} " -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" -d "{\"email\":\"ravi.kumar@example.com\",\"password\":\"guess-$i\"}" done401 401 401 401 401 401 401
What this code does
- Every guess gets a fresh answer, so the script can go on for as long as it likes.
- The 401s are correct and identical, which is good, but nothing slows the guesser down.
- This is ShopLite before
LoginAttemptService: the only cost per guess is one BCrypt check.
Credential stuffing is trying e-mail and password pairs leaked from other websites, because many people reuse one password on every app. Both attacks need nothing more than a login endpoint with no limit: a script can send hundreds of requests a second, and BCrypt slows each check but does not cap how many checks are made.
The defence is to limit failed logins: per account, so one person's password cannot be guessed, and per IP address, so one source cannot try many accounts. OWASP Top 10 2025 lists this under A07 Authentication Failures; it is risk R2 in ShopLite's threat model.
Counting failed logins with Spring Security events
An authentication event is a message Spring Security publishes after every login check: AuthenticationSuccessEvent when the password is right and AuthenticationFailureBadCredentialsEvent when it is wrong. Any bean can listen with @EventListener.
LoginAttemptService listens to both events: a failure adds one to the counters, a success resets one. Read the listeners, then the log they write.
Example 3 · src/main/java/com/shoplite/auth/LoginAttemptService.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.auth;
import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.event.EventListener;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;import org.springframework.security.authentication.event.AuthenticationSuccessEvent;import org.springframework.security.core.Authentication;import org.springframework.security.web.authentication.WebAuthenticationDetails;import org.springframework.stereotype.Service;
import com.shoplite.common.TooManyRequestsException;import com.shoplite.common.security.SecurityEventLog;import com.shoplite.user.UserPrincipal;
/** * Counts failed logins per e-mail and per IP address, and locks either one for a while when it * has too many. Spring Security announces every login result as an event; this class listens. * * The counters live in this app's memory: right for one server. With several servers behind a * load balancer, keep them in a shared store (a database table or Redis) instead. */@Service@EnableConfigurationProperties(LoginProperties.class)public class LoginAttemptService {
/** Failures inside the current window, and the moment the key is free again (null = not locked). */ private record Failures(int count, Instant windowStart, Instant lockedUntil) { }
private final Map<String, Failures> byEmail = new ConcurrentHashMap<>(); private final Map<String, Failures> byIp = new ConcurrentHashMap<>(); private final LoginProperties limits; private final SecurityEventLog events; private final Clock clock;
LoginAttemptService(LoginProperties limits, SecurityEventLog events, Clock clock) { this.limits = limits; this.events = events; this.clock = clock; }
/** Called before the password is checked: a locked e-mail or IP gets 429, even with the right password. */ public void checkAllowed(String email, String ip) { Duration wait = longest(remainingLock(byEmail, email), remainingLock(byIp, ip)); if (!wait.isZero()) { events.loginBlocked(email, ip, wait); long minutes = (wait.toSeconds() + 59) / 60; // round up: 14 min 30 s -> 15 throw new TooManyRequestsException( "Too many failed sign-ins. Try again in " + minutes + " minutes.", wait); } }
@EventListener void onFailure(AuthenticationFailureBadCredentialsEvent event) { if (!(event.getAuthentication() instanceof UsernamePasswordAuthenticationToken login)) { return; // not a password login (for example a bad bearer token) } String email = String.valueOf(login.getPrincipal()); String ip = ipOf(login); int failures = recordFailure(byEmail, email, limits.maxFailures()); recordFailure(byIp, ip, limits.maxFailuresPerIp()); events.loginFailed(email, ip, failures, limits.maxFailures()); }
@EventListener void onSuccess(AuthenticationSuccessEvent event) { Authentication auth = event.getAuthentication(); if (auth instanceof UsernamePasswordAuthenticationToken && auth.getPrincipal() instanceof UserPrincipal user) { byEmail.remove(user.getUsername()); // a correct password resets that e-mail's counter events.loginSucceeded(user.getId(), ipOf(auth)); } }
private int recordFailure(Map<String, Failures> counters, String key, int max) { Instant now = clock.instant(); Failures updated = counters.compute(key, (k, old) -> { if (old == null || now.isAfter(old.windowStart().plus(limits.window()))) { old = new Failures(0, now, null); } int count = old.count() + 1; Instant lockedUntil = count >= max ? now.plus(limits.lockDuration()) : old.lockedUntil(); return new Failures(count, old.windowStart(), lockedUntil); }); return updated.count(); }
private Duration remainingLock(Map<String, Failures> counters, String key) { Failures failures = counters.get(key); if (failures == null || failures.lockedUntil() == null) { return Duration.ZERO; } Duration left = Duration.between(clock.instant(), failures.lockedUntil()); if (left.isNegative() || left.isZero()) { counters.remove(key); return Duration.ZERO; } return left; }
private static Duration longest(Duration a, Duration b) { return a.compareTo(b) >= 0 ? a : b; }
private static String ipOf(Authentication auth) { return auth.getDetails() instanceof WebAuthenticationDetails details ? details.getRemoteAddress() : "unknown"; }}2026-10-16T13:58:47.497+05:30 INFO 14660 --- [shoplite-api] [io-18731-exec-5] shoplite.security : LOGIN_OK user=2 ip=0:0:0:0:0:0:0:1 2026-10-16T13:58:54.283+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-5] shoplite.security : LOGIN_FAILED email=r***@example.com ip=0:0:0:0:0:0:0:1 failures=1/5 2026-10-16T13:58:54.704+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-3] shoplite.security : LOGIN_FAILED email=r***@example.com ip=0:0:0:0:0:0:0:1 failures=2/5 2026-10-16T13:58:55.097+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-6] shoplite.security : LOGIN_FAILED email=r***@example.com ip=0:0:0:0:0:0:0:1 failures=3/5 2026-10-16T13:58:55.995+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-4] shoplite.security : LOGIN_FAILED email=r***@example.com ip=0:0:0:0:0:0:0:1 failures=4/5 2026-10-16T13:58:56.424+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-1] shoplite.security : LOGIN_FAILED email=r***@example.com ip=0:0:0:0:0:0:0:1 failures=5/5 2026-10-16T13:58:56.787+05:30 WARN 14660 --- [shoplite-api] [io-18731-exec-2] shoplite.security : LOGIN_BLOCKED email=r***@example.com ip=0:0:0:0:0:0:0:1 retryAfter=899s
What this code does
- Spring Security calls
onFailureandonSuccessitself; the login code does not count anything. computeupdates a counter atomically, so two requests at the same moment cannot both read 4 and write 5.- The log shows Asha's successful login, then five failures for Ravi's e-mail and the block on the sixth try (the IP
0:0:0:0:0:0:0:1is localhost in IPv6).
ShopLite's AuthenticationManager is a ProviderManager with a DaoAuthenticationProvider, and gets Spring Boot's AuthenticationEventPublisher bean. A failure adds one to the counter for that e-mail and for the caller's IP; a success resets the e-mail's counter.
The listener checks that the event comes from a password login (UsernamePasswordAuthenticationToken). Bearer-token checks on other requests are not login attempts and must not be counted.
Order of execution
One wrong password, step by step
Tap the steps in the order ShopLite handles one wrong password.
Temporary lockout, and the risk of locking out real users
A lockout refuses logins for a key, an e-mail or an IP address, for some time after too many failures. ShopLite allows 5 wrong passwords per e-mail in 15 minutes, then refuses that e-mail for 15 minutes, even with the right password.
Five wrong passwords for Ravi, then the right one, then six tries for an address that has no account.
Example 4 · Lockout in action, also for an e-mail with no account
Runs in: the shoplite-api Spring Boot project
# Five wrong passwords for Ravi, then the RIGHT one$ for i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code} " -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" -d "{\"email\":\"ravi.kumar@example.com\",\"password\":\"guess-$i\"}"; done$ curl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \ -d '{"email":"ravi.kumar@example.com","password":"ravi-dev-password"}'# Six tries for an address that has no account$ for i in 1 2 3 4 5 6; do curl -s -o /dev/null -w "%{http_code} " -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" -d "{\"email\":\"no.such.user@example.com\",\"password\":\"guess-$i\"}"; done401 401 401 401 401
HTTP/1.1 429
Retry-After: 899
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/too-many-requests","title":"Too many requests","status":429,"detail":"Too many failed sign-ins. Try again in 15 minutes.","instance":"/api/v1/auth/login"}
401 401 401 401 401 429What this code does
- After five failures even Ravi's correct password gets 429: the lock is checked before the password.
- The unknown address is locked after the same five tries, so a 429 does not reveal whether an account exists.
Retry-After: 899is the seconds left; the detail rounds it up to 15 minutes for people.
Lockout has a cost. Anyone who knows Asha's e-mail can type five wrong passwords and keep her out: a small denial of service (making a service unusable for real users). So the lock is temporary, never permanent, and the IP limit slows down the person doing it.
Count e-mails that have no account the same way as real ones. If only real accounts could be locked, a 429 would tell a stranger that the e-mail is registered.
Rate limiting by IP and by account, in the app or at the gateway
Rate limiting is capping how many requests a key may make in a time window, such as 20 failed logins per IP in 15 minutes. The account limit protects one password; the IP limit stops one machine from trying one common password on thousands of e-mails.
A small fixed-window limiter with a fake clock, so the output never depends on real time.
Example 5 · A fixed-window rate limiter with a test clock
import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;import java.util.HashMap;import java.util.Map;
class TestClock extends Clock { private Instant now = Instant.parse("2026-10-16T08:00:00Z");
void advance(Duration d) { now = now.plus(d); } @Override public Instant instant() { return now; } @Override public ZoneOffset getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(java.time.ZoneId zone) { return this; }}
class FixedWindowLimiter { private record Window(Instant start, int count) { }
private final Map<String, Window> windows = new HashMap<>(); private final int limit; private final Duration length; private final Clock clock;
FixedWindowLimiter(int limit, Duration length, Clock clock) { this.limit = limit; this.length = length; this.clock = clock; }
/** true = allowed. Each key gets `limit` requests per window. */ boolean tryAcquire(String key) { Instant now = clock.instant(); Window w = windows.get(key); if (w == null || !now.isBefore(w.start().plus(length))) { w = new Window(now, 0); // a new window starts } if (w.count() >= limit) { windows.put(key, w); return false; } windows.put(key, new Window(w.start(), w.count() + 1)); return true; }}
public class RateLimitDemo { public static void main(String[] args) { TestClock clock = new TestClock(); FixedWindowLimiter perIp = new FixedWindowLimiter(3, Duration.ofMinutes(1), clock);
StringBuilder first = new StringBuilder(); for (int i = 1; i <= 5; i++) { first.append(perIp.tryAcquire("203.0.113.7") ? "ok " : "429 "); } System.out.println("203.0.113.7, 5 tries: " + first.toString().trim()); System.out.println("198.51.100.2, 1 try: " + (perIp.tryAcquire("198.51.100.2") ? "ok" : "429"));
clock.advance(Duration.ofSeconds(61)); System.out.println("203.0.113.7 after 61 s: " + (perIp.tryAcquire("203.0.113.7") ? "ok" : "429")); }}203.0.113.7, 5 tries: ok ok ok 429 429 198.51.100.2, 1 try: ok 203.0.113.7 after 61 s: ok
What this code does
- Each key (here an IP address) gets its own counter, so one noisy client does not block another.
- A fake clock makes the test exact: moving time forward 61 seconds starts a new window.
- 203.0.113.7 and 198.51.100.2 are documentation addresses, reserved for examples. Gateways often use a token bucket instead, which smooths bursts; the idea is the same.
ShopLite counts in memory, which is right for one server. With several servers behind a load balancer each would count separately, so keep the counters in a shared store such as a database table or Redis.
Many teams also put a limit at the API gateway or load balancer (the server in front of the app), which blocks floods before they reach Java.
request.getRemoteAddr() is the proxy's address. Set server.forward-headers-strategy=native only when your own proxy writes the X-Forwarded-For header; otherwise a client could fake its IP.429 Too Many Requests and the Retry-After header
Retry-After is a response header that tells the client how many seconds to wait before trying again. It travels with the status 429 Too Many Requests, which means "you are sending too much; wait".
The exception, the new problem kind and the handler that turn a lock into a 429 answer.
Example 6 · src/main/java/com/shoplite/common/GlobalExceptionHandler.java (429 with Retry-After)
Runs in: the shoplite-api Spring Boot project
// src/main/java/com/shoplite/common/TooManyRequestsException.javapublic class TooManyRequestsException extends ShopLiteException {
private final Duration retryAfter;
public TooManyRequestsException(String message, Duration retryAfter) { super(message); this.retryAfter = retryAfter; }
public Duration getRetryAfter() { return retryAfter; }}
// ProblemKind: a new row in the contract's error tableTOO_MANY_REQUESTS(HttpStatus.TOO_MANY_REQUESTS, "too-many-requests", "Too many requests"),
// GlobalExceptionHandler/** Too many failed logins: 429 with Retry-After in seconds. */@ExceptionHandler(TooManyRequestsException.class)public ResponseEntity<ProblemDetail> handleTooManyRequests(TooManyRequestsException ex) { return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS) .header(HttpHeaders.RETRY_AFTER, String.valueOf(ex.getRetryAfter().toSeconds())) .body(ProblemKind.TOO_MANY_REQUESTS.problem(ex.getMessage()));}$ curl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" -d '{"email":"ravi.kumar@example.com","password":"ravi-dev-password"}'
HTTP/1.1 429
Retry-After: 899
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/too-many-requests","title":"Too many requests","status":429,"detail":"Too many failed sign-ins. Try again in 15 minutes.","instance":"/api/v1/auth/login"}What this code does
- The service throws a ShopLite exception with the wait time; only the handler knows about HTTP.
Retry-Aftercarries whole seconds, the simplest of its two allowed forms (seconds or a date).- The body has the same five fields as every other ShopLite error, so clients branch on
type.
A good client reads the header and shows "try again in 15 minutes" instead of retrying in a loop. ShopLite answers in the contract's Problem Details shape with a new kind, too-many-requests.
The detail is the same sentence for every locked e-mail and IP, and the lock check runs before the password is checked, so even the right password gets 429 while the lock lasts.
Next step
Check your understanding
12 quick questions