Rate Limiting Users Based on ID in ASPNET Core

Listen to this Post

Here’s how you can rate limit users based on their ID in ASP.NET Core using the built-in RateLimitPartition. This feature allows you to group users and apply rate-limiting policies dynamically.

Code Implementation

// Install required NuGet package 
// dotnet add package Microsoft.AspNetCore.RateLimiting

// Configure rate limiting in Program.cs 
builder.Services.AddRateLimiter(options => 
{ 
options.AddFixedWindowLimiter("UserBasedRateLimit", opt => 
{ 
opt.PermitLimit = 100; // Max requests per window 
opt.Window = TimeSpan.FromMinutes(1); // Time window 
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; 
opt.QueueLimit = 10; // Max queued requests 
});

// Define partition strategy by User ID 
options.RejectionStatusCode = 429; // Too Many Requests 
options.OnRejected = async (context, _) => 
{ 
await context.HttpContext.Response.WriteAsync("Too many requests. Try again later."); 
}; 
});

// Apply rate limiting to endpoints 
app.UseRateLimiter();

// Example endpoint with rate limiting 
app.MapGet("/api/user-data", () => "User data response") 
.RequireRateLimiting("UserBasedRateLimit"); 

Handling Multiple Devices for a Single User

If a user accesses your API from multiple devices, you can:
1. Track by User ID + Device ID (if available).

2. Use IP-based rate limiting as a fallback.

  1. Store request counts in a distributed cache (Redis) for scalability.
// Example: Combining User ID + Device ID 
options.AddFixedWindowLimiter("MultiDeviceRateLimit", opt => 
{ 
opt.PermitLimit = 200; // Higher limit for multi-device users 
opt.Window = TimeSpan.FromMinutes(1); 
}).PartitionBy = context => 
{ 
var userId = context.User.Identity?.Name ?? "anonymous"; 
var deviceId = context.Request.Headers["Device-ID"].FirstOrDefault() ?? "default"; 
return RateLimitPartition.Get(userId + "_" + deviceId, _ => opt); 
}; 

You Should Know:

  • Redis for Distributed Rate Limiting:
    Install Redis on Linux 
    sudo apt-get install redis-server 
    sudo systemctl enable redis 
    
  • Cloudflare Rate Limiting:

Use Cloudflare’s firewall rules for additional protection.

  • Linux Command to Monitor API Requests:
    sudo netstat -tuln | grep :5000  Check active connections 
    sudo tcpdump -i eth0 port 80 -n  Inspect HTTP traffic 
    
  • Windows Command for Network Analysis:
    Get-NetTCPConnection -LocalPort 443  Check HTTPS connections 
    

What Undercode Say:

Rate limiting is crucial for API security and fairness. While ASP.NET Core’s built-in rate limiting is effective, combining it with distributed caching (Redis) ensures scalability. For high-security applications, layer IP-based throttling alongside user-based limits. Always test under load using tools like JMeter or Postman.

Expected Output:

A secure, scalable API that prevents abuse while maintaining performance.

Reference: ASP.NET Core Rate Limiting Guide

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image