Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mr5z
Last active April 21, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/508da5ddff2494a3ba14ea0f9f98c400 to your computer and use it in GitHub Desktop.
Save mr5z/508da5ddff2494a3ba14ea0f9f98c400 to your computer and use it in GitHub Desktop.
hypersapien
//Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseIpRateLimiting();
app.UseClientRateLimiting();
// the rest
}
public void ConfigureServices(IServiceCollection services)
{
// your other configs here
...
// needed to load configuration from appsettings.json
services.AddOptions();
// needed to store rate limit counters and ip rules
services.AddMemoryCache();
//load general configuration from appsettings.json
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
//load ip rules from appsettings.json
services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));
// inject counter and rules stores
// inject counter and rules stores
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}
//Program.cs
public static async Task Main(string[] args)
{
var webHost = CreateHostBuilder(args).Build();
using (var scope = webHost.Services.CreateScope())
{
// get the ClientPolicyStore instance
var clientPolicyStore = scope.ServiceProvider.GetRequiredService<IClientPolicyStore>();
// seed client data from appsettings
await clientPolicyStore.SeedAsync();
}
await webHost.RunAsync();
}
//appsettings.json
...
"IpRateLimiting": {
"EnableEndpointRateLimiting": false,
"StackBlockedRequests": false,
"HttpStatusCode": 429,
"IpWhitelist": [ ],
"EndpointWhitelist": [ ],
"ClientWhitelist": [ ],
"GeneralRules": [
{
"Endpoint": "*",
"Period": "1s",
"Limit": 5
},
{
"Endpoint": "*",
"Period": "15m",
"Limit": 10
},
{
"Endpoint": "*",
"Period": "12h",
"Limit": 15
},
{
"Endpoint": "*",
"Period": "7d",
"Limit": 20
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment