Friday, December 12, 2025

thumbnail

Protecting Your API with Rate Limiting and IP Whitelisting in .NET

 Protecting Your API with Rate Limiting and IP Whitelisting in .NET

Introduction

APIs are critical assets, but they are also common attack targets. Without proper protection, your API can be overwhelmed by abuse, brute-force attacks, or unauthorized access. Two effective and widely used security techniques are rate limiting and IP whitelisting.

This guide explains how to implement both approaches in .NET (ASP.NET Core) to improve API security and reliability.

1. What Is Rate Limiting?

Rate limiting restricts how many requests a client can make within a specific time window.

Benefits:

Prevents abuse and DDoS-style attacks

Protects backend resources

Ensures fair usage for all clients

Improves API stability

2. Implementing Rate Limiting in ASP.NET Core (.NET 7+)

.NET provides built-in rate limiting middleware.

Step 1: Add Rate Limiting to Program.cs

using Microsoft.AspNetCore.RateLimiting;

using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =>

{

options.AddFixedWindowLimiter("fixed", limiterOptions =>

{

limiterOptions.Window = TimeSpan.FromMinutes(1);

limiterOptions.PermitLimit = 100;

limiterOptions.QueueLimit = 0;

});

});

Step 2: Enable the Middleware

var app = builder.Build();

app.UseRateLimiter();

app.MapControllers();

Step 3: Apply Rate Limiting to Endpoints

app.MapGet("/api/data", () => "Protected Data")

.RequireRateLimiting("fixed");

3. Advanced Rate Limiting Strategies

Sliding window – smoother traffic control

Token bucket – allows bursts

Partitioned rate limiting – per IP or API key

Example: Rate limit by IP

options.AddPolicy("per-ip", context =>

{

return RateLimitPartition.GetIpLimiter(

context,

ip => new FixedWindowRateLimiterOptions

{

PermitLimit = 50,

Window = TimeSpan.FromMinutes(1)

});

});

4. What Is IP Whitelisting?

IP whitelisting restricts access to your API so that only requests from approved IP addresses are allowed.

Benefits:

Blocks unauthorized clients

Reduces attack surface

Useful for internal or partner APIs

5. Implementing IP Whitelisting in ASP.NET Core

Step 1: Create IP Whitelist Middleware

public class IpWhitelistMiddleware

{

private readonly RequestDelegate _next;

private readonly HashSet<string> _allowedIps;

public IpWhitelistMiddleware(RequestDelegate next, IConfiguration config)

{

_next = next;

_allowedIps = config.GetSection("IpWhitelist").Get<HashSet<string>>() ?? new();

}

public async Task InvokeAsync(HttpContext context)

{

var remoteIp = context.Connection.RemoteIpAddress?.ToString();

if (remoteIp == null || !_allowedIps.Contains(remoteIp))

{

context.Response.StatusCode = StatusCodes.Status403Forbidden;

return;

}

await _next(context);

}

}

Step 2: Register Middleware

app.UseMiddleware<IpWhitelistMiddleware>();

Step 3: Configure Allowed IPs (appsettings.json)

"IpWhitelist": [

"192.168.1.10",

"203.0.113.25"

]

6. Handling Proxies and Load Balancers

If your API is behind a reverse proxy:

Use X-Forwarded-For headers

Configure ForwardedHeadersMiddleware

app.UseForwardedHeaders(new ForwardedHeadersOptions

{

ForwardedHeaders = ForwardedHeaders.XForwardedFor

});

7. Combining Rate Limiting and IP Whitelisting

For stronger security:

Apply IP whitelisting first

Then apply rate limiting

Use different limits for different endpoints

This layered approach is more effective than using either technique alone.

8. Best Practices

Log blocked and rate-limited requests

Use environment-based configurations

Avoid hardcoding IPs

Monitor traffic patterns

Combine with authentication and authorization

9. Common Pitfalls to Avoid

Overly strict limits causing false positives

Forgetting proxy configurations

Applying global limits without exceptions

Storing IPs directly in code

Conclusion

Rate limiting and IP whitelisting are simple yet powerful techniques to protect your .NET APIs. By implementing both, you can prevent abuse, control access, and improve the overall security and reliability of your services.

Learn Dot Net Course in Hyderabad

Read More

How to Implement OAuth 2.0 and JWT Authentication in .NET Core

Best Practices for Securing Full Stack .NET Applications

Security in Full Stack .NET

Performance Testing and Profiling in .NET Applications

Visit Our Quality Thought Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive