Skip to content

Commit

Permalink
Read rate per user rate limiter options via config
Browse files Browse the repository at this point in the history
  • Loading branch information
davidfowl committed Nov 25, 2024
1 parent fdc49bb commit 993421c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
33 changes: 24 additions & 9 deletions Todo.Api/Extensions/RateLimitExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Security.Claims;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;

namespace TodoApi;

Expand All @@ -9,7 +11,25 @@ public static class RateLimitExtensions

public static IServiceCollection AddRateLimiting(this IServiceCollection services)
{
return services.AddRateLimiter(options =>
services.AddRateLimiter();

// Setup defaults for the TokenBucketRateLimiterOptions and read them from config if defined
// In theory this could be per user using named options
services.AddOptions<TokenBucketRateLimiterOptions>()
.Configure(options =>
{
// Set defaults
options.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
options.AutoReplenishment = true;
options.TokenLimit = 100;
options.TokensPerPeriod = 100;
options.QueueLimit = 100;
})
.BindConfiguration("RateLimiting");

// Setup the rate limiting policies taking the per user rate limiting options into account
services.AddOptions<RateLimiterOptions>()
.Configure((RateLimiterOptions options, IOptionsMonitor<TokenBucketRateLimiterOptions> perUserRateLimitingOptions) =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;

Expand All @@ -20,17 +40,12 @@ public static IServiceCollection AddRateLimiting(this IServiceCollection service

return RateLimitPartition.GetTokenBucketLimiter(username, key =>
{
return new()
{
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
AutoReplenishment = true,
TokenLimit = 100,
TokensPerPeriod = 100,
QueueLimit = 100,
};
return perUserRateLimitingOptions.CurrentValue;
});
});
});

return services;
}

public static IEndpointConventionBuilder RequirePerUserRateLimit(this IEndpointConventionBuilder builder)
Expand Down
16 changes: 4 additions & 12 deletions Todo.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,9 @@
"Microsoft.AspNetCore": "Information"
}
},
"Authentication": {
"Schemes": {
"Bearer": {
"ValidAudiences": [
"http://localhost:47743",
"https://localhost:44371",
"http://localhost:5000",
"https://localhost:5001"
],
"ValidIssuer": "dotnet-user-jwts"
}
}
"RateLimiting": {
"TokenLimit": 50,
"TokensPerPeriod": 50,
"QueueLimit": 50
}
}

0 comments on commit 993421c

Please sign in to comment.