stefanprodan / AspNetCoreRateLimit

ASP.NET Core rate limiting middleware
MIT License
3.11k stars 447 forks source link

X-Forwarded-For #412

Open MarkCiliaVincenti opened 1 year ago

MarkCiliaVincenti commented 1 year ago

AspNetCoreRateLimit supports X-Real-IP but not X-Forwarded-For

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

Please note that X-Forwarded-For elements are comma-separated, with optional whitespace surrounding the commas. Only the first element is useful for us and this first element should be considered equivalent to X-Real-IP to the best of my knowledge.

chaosifier commented 4 months ago

Have you considered adding the X-Real-IP header through middleware? Here's an example:

app.Use(async (context, next) =>
{
    string xfwdheader = "X-Forwarded-For";
    string realipheader = "X-Real-IP";
    if (context.Request.Headers.ContainsKey(xfwdheader) && !context.Request.Headers.ContainsKey(realipheader))
    {
        var originatingAddressTrail = context.Request.Headers[xfwdheader].ToString();
        var parts = originatingAddressTrail.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length > 0) {
            var clientIp = parts[0].Trim();
            context.Request.Headers.Append(realipheader, new Microsoft.Extensions.Primitives.StringValues(clientIp));
        }
    }
    await next.Invoke();
});