Skip to content

feat: rate limiting configuration with IP-based partitioning #269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Dotnet.Samples.AspNetCore.WebApi.Configurations;

/// <summary>
/// Configuration options for the Fixed Window Rate Limiter.
/// </summary>
public class RateLimiterConfiguration
{
/// <summary>
/// Gets or sets the maximum number of permits that can be leased per window.
/// Default value is 60 requests.
/// </summary>
public int PermitLimit { get; set; } = 60;

/// <summary>
/// Gets or sets the time window in seconds for rate limiting.
/// Default value is 60 seconds (1 minute).
/// </summary>
public int WindowSeconds { get; set; } = 60;

/// <summary>
/// Gets or sets the maximum number of requests that can be queued when the permit limit is exceeded.
/// A value of 0 means no queuing (default).
/// </summary>
public int QueueLimit { get; set; } = 0;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,8 @@
</PropertyGroup>

<ItemGroup Label="Development dependencies">
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6" PrivateAssets="all" />
</ItemGroup>

<ItemGroup Label="Runtime dependencies">
Expand All @@ -23,6 +18,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.6" />
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="FluentValidation" Version="12.0.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
namespace Dotnet.Samples.AspNetCore.WebApi.Extensions;

/// <summary>
/// Extension methods for WebApplicationBuilder to encapsulate service configuration.
/// Extension methods for IServiceCollection to encapsulate service configuration.
/// </summary>
public static class ServiceCollectionExtensions
public static partial class ServiceCollectionExtensions
{
/// <summary>
/// Adds DbContextPool with SQLite configuration for PlayerDbContext.
Expand Down Expand Up @@ -54,16 +54,25 @@ IWebHostEnvironment environment
/// <see href="https://learn.microsoft.com/en-us/aspnet/core/security/cors"/>
/// </summary>
/// <param name="services">The IServiceCollection instance.</param>
/// <param name="environment">The web host environment.</param>
/// <returns>The IServiceCollection for method chaining.</returns>
public static IServiceCollection AddCorsDefaultPolicy(this IServiceCollection services)
public static IServiceCollection AddCorsDefaultPolicy(
this IServiceCollection services,
IWebHostEnvironment environment
)
{
services.AddCors(options =>
if (environment.IsDevelopment())
{
options.AddDefaultPolicy(corsBuilder =>
services.AddCors(options =>
{
corsBuilder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
options.AddDefaultPolicy(corsBuilder =>
{
corsBuilder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});
});
}

// No CORS configured in Production or other environments

return services;
}
Expand Down Expand Up @@ -96,7 +105,9 @@ IConfiguration configuration
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", configuration.GetSection("OpenApiInfo").Get<OpenApiInfo>());
var openApiInfo = configuration.GetSection("OpenApiInfo").Get<OpenApiInfo>();

options.SwaggerDoc("v1", openApiInfo);
options.IncludeXmlComments(SwaggerUtilities.ConfigureXmlCommentsFilePath());
options.AddSecurityDefinition("Bearer", SwaggerUtilities.ConfigureSecurityDefinition());
options.OperationFilter<AuthorizeCheckOperationFilter>();
Expand Down Expand Up @@ -143,4 +154,47 @@ public static IServiceCollection RegisterPlayerRepository(this IServiceCollectio
services.AddScoped<IPlayerRepository, PlayerRepository>();
return services;
}

/// <summary>
/// Adds rate limiting configuration with IP-based partitioning.
/// <br />
/// <see href="https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit"/>
/// </summary>
/// <param name="services">The IServiceCollection instance.</param>
/// <param name="configuration">The application configuration instance.</param>
/// <returns>The IServiceCollection for method chaining.</returns>
public static IServiceCollection AddFixedWindowRateLimiter(
this IServiceCollection services,
IConfiguration configuration
)
{
var settings =
configuration.GetSection("RateLimiter").Get<RateLimiterConfiguration>()
?? new RateLimiterConfiguration();

services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
httpContext =>
{
var partitionKey = HttpContextUtilities.ExtractIpAddress(httpContext);

return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: partitionKey,
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = settings.PermitLimit,
Window = TimeSpan.FromSeconds(settings.WindowSeconds),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = settings.QueueLimit
}
);
}
);

options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});

return services;
}
}
16 changes: 8 additions & 8 deletions src/Dotnet.Samples.AspNetCore.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@

/* Controllers -------------------------------------------------------------- */

builder.Services.AddControllers();
builder.Services.AddCorsDefaultPolicy();
builder.Services.AddHealthChecks();
builder.Services.AddControllers();
builder.Services.AddValidators();
builder.Services.AddCorsDefaultPolicy(builder.Environment);
builder.Services.AddFixedWindowRateLimiter(builder.Configuration);

if (builder.Environment.IsDevelopment())
{
Expand Down Expand Up @@ -54,17 +55,16 @@
* -------------------------------------------------------------------------- */

app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.MapHealthChecks("/health");
app.UseRateLimiter();
app.MapControllers();

if (app.Environment.IsDevelopment())
{
app.UseCors();
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors();
app.UseRateLimiter();
app.MapHealthChecks("/health");
app.MapControllers();

await app.RunAsync();
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Net;

namespace Dotnet.Samples.AspNetCore.WebApi.Utilities;

/// <summary>
/// Utility class for HTTP context operations.
/// </summary>
public static class HttpContextUtilities
{
/// <summary>
/// This method checks for the "X-Forwarded-For" and "X-Real-IP" headers,
/// which are commonly used by proxies to forward the original client IP address.
/// If these headers are not present or the IP address cannot be parsed,
/// it falls back to the remote IP address from the connection.
/// If no valid IP address can be determined, it returns "unknown".
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The client IP address or "unknown" if not available.</returns>
public static string ExtractIpAddress(HttpContext httpContext)
{
ArgumentNullException.ThrowIfNull(httpContext);

var headers = httpContext.Request.Headers;
IPAddress? ipAddress;

if (headers.TryGetValue("X-Forwarded-For", out var xForwardedFor))
{
var clientIp = xForwardedFor
.ToString()
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.FirstOrDefault();

if (!string.IsNullOrWhiteSpace(clientIp) && IPAddress.TryParse(clientIp, out ipAddress))
return ipAddress.ToString();
}

if (
headers.TryGetValue("X-Real-IP", out var xRealIp)
&& IPAddress.TryParse(xRealIp.ToString(), out ipAddress)
)
{
return ipAddress.ToString();
}

return httpContext.Connection.RemoteIpAddress?.ToString() ?? $"unknown-{Guid.NewGuid()}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@
"Name": "MIT License",
"Url": "https://opensource.org/license/mit"
}
},
"RateLimiter": {
"PermitLimit": 60,
"WindowSeconds": 60,
"QueueLimit": 0
}
}
5 changes: 5 additions & 0 deletions src/Dotnet.Samples.AspNetCore.WebApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@
"Name": "MIT License",
"Url": "https://opensource.org/license/mit"
}
},
"RateLimiter": {
"PermitLimit": 60,
"WindowSeconds": 60,
"QueueLimit": 0
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,12 @@
</PropertyGroup>

<ItemGroup Label="Test dependencies">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Moq" Version="4.20.72">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.3.0">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.9.3">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.3">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.4">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" PrivateAssets="all" />
<PackageReference Include="Moq" Version="4.20.72" PrivateAssets="all" />
<PackageReference Include="FluentAssertions" Version="8.3.0" PrivateAssets="all" />
<PackageReference Include="xunit" Version="2.9.3" PrivateAssets="all" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.3" PrivateAssets="all" />
<PackageReference Include="coverlet.collector" Version="6.0.4" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
Expand Down