I’ve run into a problem with setting up rate limits for my application. The main idea is to enable a global rate limit (affecting all endpoints) but being able to disable it for certain API endpoints and enable another rate limit for them, so we can have less restrictive ones for those endpoints.
We tried creating both: a global rate limit middleware and a api rate limit middleware. Both middlewares work but the API specific one doesnt overwrite the global one. (Always both are applied) How can I change that?
builder.Services.AddRateLimiter(limiterOptions =>
{
limiterOptions.OnRejected = (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);
}
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
GetUserEndPoint(context.HttpContext));
return new ValueTask();
};
limiterOptions.AddPolicy(userPolicyName, context =>
{
var username = "anonymous user";
if (context.User.Identity?.IsAuthenticated is true)
{
//await context.GetTokenAsync(JwtBearerDefaults, AuthenticationScheme, "access_token");
username = context.Request.Headers.Authorization!;
}
return RateLimitPartition.GetFixedWindowLimiter(username,
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = myOptions.TokenLimit2,
Window = TimeSpan.FromSeconds(myOptions.Window),
});
});
limiterOptions.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, IPAddress>(context =>
{
var test = context.Request.Host;
IPAddress? remoteIpAddress = context.Connection.RemoteIpAddress;
if (IPAddress.IsLoopback(remoteIpAddress!))
{
return RateLimitPartition.GetSlidingWindowLimiter
(remoteIpAddress!,
_ => new SlidingWindowRateLimiterOptions
{
PermitLimit = myOptions.PermitLimit,
//QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
//QueueLimit = myOptions.QueueLimit,
Window = TimeSpan.FromSeconds(myOptions.Window),
SegmentsPerWindow = myOptions.SegmentsPerWindow
});
}
return RateLimitPartition.GetNoLimiter(IPAddress.Loopback);
});
I use Rate Limiting middleware
in Asp.net core 7
.