---
title: Implement Brute-force Protection
impact: HIGH
impactDescription: prevents automated password guessing and account harvesting attacks
tags: brute-force, rate-limiting, authentication, security, kotlin
---

## Implement Brute-force Protection

Authentication endpoints without rate limiting or lockout mechanisms are vulnerable to brute-force attacks, where attackers try thousands of common passwords or perform "credential stuffing" attacks using stolen credentials.

**Incorrect (no protection):**

```kotlin
@PostMapping("/login")
fun login(@RequestBody data: LoginRequest): ResponseEntity<Any> {
    val result = authService.authenticate(data.username, data.password)
    // No limit on attempts. Attacker can call this 10,000 times a minute.
    return ResponseEntity.ok(result)
}
```

**Correct (rate limiting and account lockout):**

```kotlin
// Using Ktor RateLimiting
install(RateLimit) {
    register(RateLimitName("login")) {
        rateLimiter(limit = 5, refillPeriod = 15.minutes)
    }
}

// In-code tracking and exponential backoff
class LoginService(private val redisTemplate: RedisTemplate<String, Int>) {
    fun handleLogin(username: String) {
        val attempts = redisTemplate.get("login_attempts:$username") ?: 0
        
        if (attempts >= 5) {
            val lockoutMinutes = Math.pow(2.0, (attempts - 5).toDouble()).toLong()
            throw LockedException("Account locked for $lockoutMinutes minutes")
        }
        
        try {
            authenticate(username)
            redisTemplate.delete("login_attempts:$username")
        } catch (e: Exception) {
            redisTemplate.increment("login_attempts:$username")
            throw e
        }
    }
}

// Spring Security Configuration
// Use standard LoginFailureHandler to increment counters.
```

**Brute-Force Protection Strategies:**
- **Rate Limiting:** Limit requests by IP and by username.
- **Account Lockout:** Temporarily disable accounts after X failed attempts.
- **Exponential Backoff:** Increase the wait time between successive login attempts.
- **CAPTCHA:** Use CAPTCHA challenges after a few failed attempts.
- **WAF:** Use a Web Application Firewall to block high-frequency attacks.

**Tools:** Spring Security (LoginFailureHandler), Redis, Ktor RateLimit, Cloudflare WAF, reCAPTCHA
