|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Microsoft.Extensions.Options; |
| 4 | +using System.Threading.RateLimiting; |
| 5 | + |
| 6 | +namespace OrchardCoreContrib.HealthChecks; |
| 7 | + |
| 8 | +public class HealthChecksRateLimitingMiddleware |
| 9 | +{ |
| 10 | + private readonly RequestDelegate _next; |
| 11 | + private readonly HealthChecksOptions _healthChecksOptions; |
| 12 | + private readonly SlidingWindowRateLimiter _rateLimiter; |
| 13 | + private readonly ILogger _logger; |
| 14 | + |
| 15 | + public HealthChecksRateLimitingMiddleware( |
| 16 | + RequestDelegate next, |
| 17 | + IOptions<HealthChecksOptions> healthChecksOptions, |
| 18 | + IOptions<HealthChecksRateLimitingOptions> healthChecksRateLimitingOptions, |
| 19 | + ILogger<HealthChecksRateLimitingMiddleware> logger) |
| 20 | + { |
| 21 | + var healthChecksRateLimitingOptionsValue = healthChecksRateLimitingOptions.Value; |
| 22 | + _rateLimiter = new(new SlidingWindowRateLimiterOptions |
| 23 | + { |
| 24 | + PermitLimit = healthChecksRateLimitingOptionsValue.PermitLimit, |
| 25 | + Window = healthChecksRateLimitingOptionsValue.Window, |
| 26 | + SegmentsPerWindow = healthChecksRateLimitingOptionsValue.SegmentsPerWindow, |
| 27 | + QueueLimit = healthChecksRateLimitingOptionsValue.QueueLimit, |
| 28 | + QueueProcessingOrder = QueueProcessingOrder.OldestFirst |
| 29 | + }); |
| 30 | + _next = next; |
| 31 | + _healthChecksOptions = healthChecksOptions.Value; |
| 32 | + _logger = logger; |
| 33 | + } |
| 34 | + |
| 35 | + public async Task InvokeAsync(HttpContext context) |
| 36 | + { |
| 37 | + if (context.Request.Path.Equals(_healthChecksOptions.Url)) |
| 38 | + { |
| 39 | + var rateLimitLease = _rateLimiter.AttemptAcquire(1); |
| 40 | + |
| 41 | + if (!rateLimitLease.IsAcquired) |
| 42 | + { |
| 43 | + _logger.LogWarning("Rate limit exceeded for IP Address {RemoteIP}.", context.Connection.RemoteIpAddress); |
| 44 | + |
| 45 | + context.Response.StatusCode = StatusCodes.Status429TooManyRequests; |
| 46 | + |
| 47 | + await context.Response.WriteAsync("Too Many Requests."); |
| 48 | + |
| 49 | + return; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + await _next(context); |
| 54 | + } |
| 55 | +} |
0 commit comments