How does ASP.NET Core determine the original client IP address and scheme (HTTP/HTTPS) when running behind a reverse proxy that terminates TLS and forwards requests, given the app only sees the proxy's connection?
Short answer
Behind a reverse proxy, HttpContext.Connection.RemoteIpAddress and Request.Scheme by default reflect the proxy's own connection details, not the original client's -- the ForwardedHeadersMiddleware (UseForwardedHeaders()) reads standard X-Forwarded-For, X-Forwarded-Proto, and…
Advertisement
AModel answer
Behind a reverse proxy, HttpContext.Connection.RemoteIpAddress and Request.Scheme by default reflect the proxy's own connection details, not the original client's -- the ForwardedHeadersMiddleware (UseForwardedHeaders()) reads standard X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host headers set by the proxy and rewrites these values to the actual original client information, which must be explicitly enabled and configured with the trusted proxy's IP range for security.
builder.Services.Configure<ForwardedHeadersOptions>(options => {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownProxies.Add(IPAddress.Parse("10.0.0.5")); // trust only this specific proxy
});
var app = builder.Build();
app.UseForwardedHeaders(); // must run early in the pipeline, before other middleware relying on client IP/schemeReal-world example
An API behind an nginx reverse proxy enables ForwardedHeadersMiddleware configured with nginx's known internal IP, correctly recovering the true external client IP address for rate-limiting and audit logging purposes instead of seeing nginx's own internal IP for every single request.
Likely follow-ups
- What security risk exists if you trust X-Forwarded-For headers from untrusted or unconfigured sources?
- Why must UseForwardedHeaders() run before other middleware that depend on the client IP or scheme?
Related topics