---
title: Implement Brute-force Protection
impact: MEDIUM
impactDescription: prevents password guessing attacks
tags: brute-force, rate-limiting, authentication, security
---

## Implement Brute-force Protection

Without rate limiting, attackers can try millions of password combinations.

**Incorrect (no protection):**

```go
func LoginHandler(w http.ResponseWriter, r *http.Request) {
    user, err := authenticate(r.FormValue("email"), r.FormValue("password"))
    // No limit on attempts!
    if err != nil {
        http.Error(w, "Invalid credentials", 401)
        return
    }
}
```

**Correct (rate limiting with middleware):**

```go
import "golang.org/x/time/rate"

var loginLimiter = rate.NewLimiter(rate.Every(3*time.Minute), 5) // 5 attempts per window

func LoginHandler(w http.ResponseWriter, r *http.Request) {
    if !loginLimiter.Allow() {
        http.Error(w, "Too many login attempts", 429)
        return
    }

    user, err := authenticate(r.FormValue("email"), r.FormValue("password"))
    // ...
}

// Better: persistent rate limiting via Redis
func RateLimitMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        key := "login_limit:" + r.RemoteAddr
        if isRateLimited(key) {
            http.Error(w, "Too many attempts", 429)
            return
        }
        next.ServeHTTP(w, r)
    })
}
```

**Tools:** `golang.org/x/time/rate`, Redis, WAF
