AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

Rate limit policy settings is not applied using AspNetCoreRateLimit in .net core 6

Open arash3003 opened this issue 3 years ago • 14 comments

Hi, I am using AspNetCoreRateLimit version 4.0.1 and I have done all the setup in .net core 6 web api. I can see rate limit is working when I send a call via postman.

However, when I add IpRateLimitPolicies with specific IP address, the settings won't be applied. I use postman and this time in the proxy I added the ip address to 127.0.0.1. I can see the ip hitting the api is set correctly when I use Request.HttpContext.Connection.RemoteIpAddress; I also deployed to our dev environment and called from a different client and got the same result.

I registered them as follow in program.cs: _serviceCollection.AddOptions(); _serviceCollection.AddMemoryCache(); _serviceCollection.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting")); _serviceCollection.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies")); _serviceCollection.AddInMemoryRateLimiting(); _serviceCollection.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>(); _serviceCollection.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); _serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); _serviceCollection.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

Also added: app.UseIpRateLimiting();

My appsettings also looks like: { "IpRateLimiting": { "EnableEndpointRateLimiting": false, "StackBlockedRequests": false, "RealIPHeader": "X-Real-IP", "ClientIdHeader": "X-ClientId", "IpWhitelist": [ ], "EndpointWhitelist": [], "ClientWhitelist": [], "HttpStatusCode": 429, "GeneralRules": [ { "Endpoint": "*", "Period": "10s", "Limit": 1 } ] }, "IpRateLimitPolicies": { "IpRules": [ { "Ip": "127.0.0.1", "Rules": [ { "Endpoint": "*", "Period": "20s", "Limit": 2 } ] } ] }

But apparently the settings under IpRateLimitPolicies won't be applied.

I wonder if I have missed anything here?

Thank you

arash3003 avatar Feb 13 '22 18:02 arash3003

any thoughts on this?

arash3003 avatar Feb 18 '22 00:02 arash3003

Same issue here, my ratelimit rules are not applying either

ghost avatar Feb 19 '22 12:02 ghost

thanks your register code,it work for me. I cannot find any register code for .NET 6 before..

MAYBreath avatar Feb 23 '22 15:02 MAYBreath

Thanks @MAYBreath - are the settings under "IpRateLimitPolicies" applied for you in .net core 6? have you done anything extra?

arash3003 avatar Feb 23 '22 18:02 arash3003

IpRateLimitPolicies

@arash3003 yes,you need add those code at Program.cs var ipPolicyStore = app.Services.GetRequiredService<IIpPolicyStore>(); ipPolicyStore.SeedAsync().GetAwaiter().GetResult(); var clientPolicyStore = app.Services.GetRequiredService<IClientPolicyStore>(); clientPolicyStore.SeedAsync().GetAwaiter().GetResult();

and if you test at localhost,try change "Ip": "127.0.0.1" to "Ip": "::1/10" ,it may help you.

MAYBreath avatar Feb 24 '22 02:02 MAYBreath

Thanks - it works now for both IP and Client.

arash3003 avatar Apr 12 '22 22:04 arash3003

Hi @MAYBreath & @arash3003

I am also facing same issue in .net core 5, Do you have any solution on this?

// needed to store rate limit counters and ip rules services.AddMemoryCache();

        //load general configuration from appsettings.json
        services.Configure<ClientRateLimitOptions>(_config.GetSection("ClientRateLimiting"));

        //load client rules from appsettings.json
        services.Configure<ClientRateLimitPolicies>(_config.GetSection("ClientRateLimitPolicies"));

        services.AddInMemoryRateLimiting();

        // inject counter and rules stores
        services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
        services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();

MohammedMubeen avatar May 23 '22 09:05 MohammedMubeen

HI @MAYBreath - Its working fine, Thanks

app.UseExceptionMiddleware();

        app.UseHttpsRedirection();

        app.UseRouting();

        var clientPolicyStore = Services.GetRequiredService<IClientPolicyStore>(); 
        clientPolicyStore.SeedAsync().GetAwaiter().GetResult();

        app.UseClientRateLimiting();

        app.UseCors(x => x.SetIsOriginAllowed(origin => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseDefaultFiles();


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

MohammedMubeen avatar May 23 '22 09:05 MohammedMubeen

Hi @MohammedMubeen , yes it worked for me after I applied @MAYBreath's solution.

arash3003 avatar May 23 '22 18:05 arash3003

Hi @arash3003 ,

Thanks for the response.

If possible , Set periods and Limit from the database? Do you have any idea?

"GeneralRules": [ { "Endpoint": "*", "Period": "1s", "Limit": 2 } ]

My clients, They expecting provide request limitation based on there subscription. Example like - Basic, Premium & Enterprise. Do you have any idea?

MohammedMubeen avatar May 23 '22 19:05 MohammedMubeen

Yes you can do it easily. This is the same way I have implemented. You can create your tables and have your methods to extract data from the DB. Then you can do something like this is your startup.cs. In my example I use the client policy:

ClientRateLimitPolicies policies = MYDBRepo.GetAll().GetAwaiter().GetResult();

_serviceCollection.AddOptions();
_serviceCollection.AddMemoryCache();
_serviceCollection.Configure<ClientRateLimitOptions>(Configuration.GetSection("ClientRateLimiting"));
_serviceCollection.Configure<ClientRateLimitPolicies>(option => { option.ClientRules = policies.ClientRules; });

MYDBRepo returns all active policies and map it to ClientRateLimitPolicies.

arash3003 avatar May 23 '22 19:05 arash3003

Thanks @arash3003 .

Now I got some ideas. If any help, Please let you know.

Again, Thanks for the help.

MohammedMubeen avatar May 23 '22 19:05 MohammedMubeen

Hello,

You need to add below code as middleware.

var clientPolicyStore = app.Services.GetRequiredService<IClientPolicyStore>(); clientPolicyStore.SeedAsync().GetAwaiter().GetResult();

Thank you

ankitmori avatar Mar 20 '23 10:03 ankitmori

Hi

I am facing same issue while applying rate limiting in net core 6 project with AspNetCoreRateLimit version is 5.0.0. I am fetching Rate Limit Options from appsettings.json and even tries following middleware before app.UseIpRateLimiting(); in Configure method in startup

var ipPolicyStore = app.ApplicationServices.GetRequiredService<IIpPolicyStore>(); ipPolicyStore.SeedAsync().GetAwaiter().GetResult();

But it still didn't work for me. Did anyone resolve it? Appreciate the support!

majid20222 avatar Apr 23 '24 11:04 majid20222