In this lesson, you will learn how to defend your authentication endpoints against brute-force and denial-of-service attacks by implementing request rate limiting.
Why Throttle Authentication?
When dealing with identity, your login and registration endpoints are the most sensitive parts of your application. If an attacker can send thousands of requests per second, they can attempt to brute-force passwords or overwhelm your database with authentication queries. Rate limiting acts as a bouncer at the door, ensuring that no single user or IP address can flood the system with authentication requests.
Implementing Fixed Window Limiting
The simplest approach is the "Fixed Window" strategy, which limits a client to a specific number of requests within a defined time frame (e.g., 5 requests every 60 seconds).
In modern ASP.NET Core, we apply this globally or specifically to endpoints using the Microsoft.AspNetCore.RateLimiting middleware. To protect your identity endpoints specifically, you can use the RequireRateLimiting extension:
var authPolicy = "auth-limit-policy";
builder.Services.AddRateLimiter(options => {
options.AddFixedWindowLimiter(authPolicy, opt => {
opt.PermitLimit = 3; // Only 3 attempts
opt.Window = TimeSpan.FromMinutes(1); // per minute
opt.QueueLimit = 0; // Reject immediately if limit reached
});
});
// In your Program.cs
app.MapPost("/login", () => { /* ... */ })
.RequireRateLimiting(authPolicy);
Strategic Throttling
When applying this to identity, you must choose your "partition key" wisely. If you rate limit by IP address, you risk blocking legitimate users behind a corporate proxy or NAT. However, in the context of an unauthenticated login endpoint, the IP is often your only identifier.
To harden this, consider using a Sliding Window or Token Bucket algorithm for more granular control. This allows users a "burst" of attempts while strictly enforcing a sustainable average rate over time, which is much friendlier for legitimate users who might mistype their password once or twice.
By integrating this at the middleware layer, you stop malicious traffic before it ever hits your heavy database-bound authentication logic, preserving your server resources for authorized traffic.
Key Takeaway: Implement rate limiting on all authentication endpoints to transform a potential brute-force attack into a manageable, rejected traffic pattern.