11using System . Security . Claims ;
22using System . Threading . RateLimiting ;
3+ using Microsoft . AspNetCore . RateLimiting ;
4+ using Microsoft . Extensions . Options ;
35
46namespace 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 )
0 commit comments