diff --git a/SfeduSchedule/Program.cs b/SfeduSchedule/Program.cs index cb3433a..25adae8 100644 --- a/SfeduSchedule/Program.cs +++ b/SfeduSchedule/Program.cs @@ -5,6 +5,7 @@ using SfeduSchedule; using SfeduSchedule.Jobs; using SfeduSchedule.Services; using X.Extensions.Logging.Telegram.Extensions; +using Microsoft.AspNetCore.HttpOverrides; var builder = WebApplication.CreateBuilder(args); @@ -76,7 +77,9 @@ builder.Services.AddRateLimiter(options => { options.AddPolicy("throttle", httpContext => RateLimitPartition.GetFixedWindowLimiter( - partitionKey: httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown", + partitionKey: (httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var xff) && !string.IsNullOrWhiteSpace(xff.ToString())) + ? xff.ToString().Split(',')[0].Trim() + : (httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown"), factory: _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, @@ -92,11 +95,21 @@ builder.Services.AddRateLimiter(options => cancellationToken); var reqLogger = context.HttpContext.RequestServices.GetRequiredService>(); - reqLogger.LogWarning("Rate limit exceeded for IP: {IpAddress}", - context.HttpContext.Connection.RemoteIpAddress); + var clientIp = (context.HttpContext.Request.Headers.TryGetValue("X-Forwarded-For", out var xff) && !string.IsNullOrWhiteSpace(xff.ToString())) + ? xff.ToString().Split(',')[0].Trim() + : context.HttpContext.Connection.RemoteIpAddress?.ToString(); + reqLogger.LogWarning("Rate limit exceeded for IP: {IpAddress}", clientIp); }; }); +builder.Services.Configure(options => +{ + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | + ForwardedHeaders.XForwardedProto; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); +}); + var app = builder.Build(); var logger = app.Services.GetRequiredService>(); diff --git a/docker-compose-prod.yml b/docker-compose-prod.yml index 2208b32..33b278d 100644 --- a/docker-compose-prod.yml +++ b/docker-compose-prod.yml @@ -4,6 +4,7 @@ services: - '8088:8080' container_name: SfeduSchedule environment: + - ASPNETCORE_FORWARDEDHEADERS_ENABLED=true - AzureAd:Instance=https://login.microsoftonline.com/ - AzureAd:TenantId=sfedu.ru - AzureAd:ClientId= diff --git a/docker-compose-test.yml b/docker-compose-test.yml index 85db821..b1a5944 100644 --- a/docker-compose-test.yml +++ b/docker-compose-test.yml @@ -4,6 +4,7 @@ services: - '8088:8080' container_name: SfeduSchedule environment: + - ASPNETCORE_FORWARDEDHEADERS_ENABLED=true - AzureAd:Instance=https://login.microsoftonline.com/ - AzureAd:TenantId=sfedu.ru - AzureAd:ClientId=