Skip to content

Commit 993421c

Browse files
committed
Read rate per user rate limiter options via config
1 parent fdc49bb commit 993421c

File tree

2 files changed

+28
-21
lines changed

2 files changed

+28
-21
lines changed

Todo.Api/Extensions/RateLimitExtensions.cs

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
using System.Security.Claims;
22
using System.Threading.RateLimiting;
3+
using Microsoft.AspNetCore.RateLimiting;
4+
using Microsoft.Extensions.Options;
35

46
namespace TodoApi;
57

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

1012
public static IServiceCollection AddRateLimiting(this IServiceCollection services)
1113
{
12-
return services.AddRateLimiter(options =>
14+
services.AddRateLimiter();
15+
16+
// Setup defaults for the TokenBucketRateLimiterOptions and read them from config if defined
17+
// In theory this could be per user using named options
18+
services.AddOptions<TokenBucketRateLimiterOptions>()
19+
.Configure(options =>
20+
{
21+
// Set defaults
22+
options.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
23+
options.AutoReplenishment = true;
24+
options.TokenLimit = 100;
25+
options.TokensPerPeriod = 100;
26+
options.QueueLimit = 100;
27+
})
28+
.BindConfiguration("RateLimiting");
29+
30+
// Setup the rate limiting policies taking the per user rate limiting options into account
31+
services.AddOptions<RateLimiterOptions>()
32+
.Configure((RateLimiterOptions options, IOptionsMonitor<TokenBucketRateLimiterOptions> perUserRateLimitingOptions) =>
1333
{
1434
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
1535

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

2141
return RateLimitPartition.GetTokenBucketLimiter(username, key =>
2242
{
23-
return new()
24-
{
25-
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
26-
AutoReplenishment = true,
27-
TokenLimit = 100,
28-
TokensPerPeriod = 100,
29-
QueueLimit = 100,
30-
};
43+
return perUserRateLimitingOptions.CurrentValue;
3144
});
3245
});
3346
});
47+
48+
return services;
3449
}
3550

3651
public static IEndpointConventionBuilder RequirePerUserRateLimit(this IEndpointConventionBuilder builder)

Todo.Api/appsettings.Development.json

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,9 @@
55
"Microsoft.AspNetCore": "Information"
66
}
77
},
8-
"Authentication": {
9-
"Schemes": {
10-
"Bearer": {
11-
"ValidAudiences": [
12-
"http://localhost:47743",
13-
"https://localhost:44371",
14-
"http://localhost:5000",
15-
"https://localhost:5001"
16-
],
17-
"ValidIssuer": "dotnet-user-jwts"
18-
}
19-
}
8+
"RateLimiting": {
9+
"TokenLimit": 50,
10+
"TokensPerPeriod": 50,
11+
"QueueLimit": 50
2012
}
2113
}

0 commit comments

Comments
 (0)