AspNetCoreRateLimit icon indicating copy to clipboard operation
AspNetCoreRateLimit copied to clipboard

X-Forwarded-For

Open MarkCiliaVincenti opened this issue 3 years ago • 1 comments

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.

MarkCiliaVincenti avatar Jan 23 '23 09:01 MarkCiliaVincenti

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();
});

chaosifier avatar May 24 '24 04:05 chaosifier