skip to content

Proxies & Forwarded Headers

Running behind Nginx or a load balancer: UseForwardedHeaders restoring client IP and scheme, trusted KnownProxies, and UsePathBase. Interviewers ask why redirects and links break without it.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

Behind a TLS-terminating load balancer, why does an ASP.NET Core app log the balancer's IP and build http:// links, and what does UseForwardedHeaders change?

level: juniorimportance: must knowfreq 55%

answer

  1. the proxy opens the TCP connection
  2. Connection.RemoteIpAddress and Request.Scheme
  3. X-Forwarded-For and X-Forwarded-Proto
  4. ForwardedHeaders defaults to None
  5. only loopback senders trusted by default

basics

~20 s

Kestrel only sees the balancer's plain-HTTP connection, so RemoteIpAddress is the balancer and Scheme is http. UseForwardedHeaders, told to process X-Forwarded-For and X-Forwarded-Proto from a trusted proxy, writes the client's IP and https scheme back onto HttpContext.

solid answer

~40 s

The load balancer terminates TLS and opens its own HTTP connection to Kestrel, so `HttpContext.Connection.RemoteIpAddress` is the balancer's address and `Request.Scheme` is `http`. Everything derived from them inherits the error: absolute links and OIDC redirect URIs come out as `http://`, `UseHttpsRedirection` can redirect forever, and logs and per-client limits see one client. The balancer records the truth in `X-Forwarded-For` and `X-Forwarded-Proto`; `app.UseForwardedHeaders()` reads them and overwrites `RemoteIpAddress`, `Scheme` (and `Host` or `PathBase` if enabled), keeping the old values in `X-Original-*` headers. Two defaults catch people: `ForwardedHeadersOptions.ForwardedHeaders` is `None`, so you must name the headers to process, and only senders in `KnownProxies` / `KnownIPNetworks` (loopback by default) are believed. Register it early, before anything that reads the scheme or the client IP.

code

http · 4 lines
http
GET /passes/season HTTP/1.1
Host: lifts.example.com
X-Forwarded-For: 203.0.113.42
X-Forwarded-Proto: https

go deeper

for a junior

Recall that behind a proxy the connection belongs to the proxy, and that X-Forwarded-For and X-Forwarded-Proto carry the client's IP and scheme into the app.

for a middle

Explain which HttpContext values the middleware overwrites, that ForwardedHeaders defaults to None, and that only senders in KnownProxies or KnownIPNetworks are believed.

for a senior

Diagnose a redirect loop or wrong client IP from logs: check the Unknown proxy debug line, the X-Original-For header and whether the middleware runs before its consumers.

for a principal

Weigh where client identity is established in a layered edge: which hop is trusted, how that trust is configured per environment, and who owns it when the topology changes.

## What Kestrel sees behind a proxy Kestrel, ASP.NET Core's built-in web server, knows only the TCP connection it accepted and the HTTP request on it. Picture a ski resort's **lift-pass shop**: skiers' browsers connect over HTTPS to a load balancer, the balancer **terminates TLS** (decrypts the request) and forwards plain HTTP to Kestrel from its own address, say `10.0.0.10`. From the app's point of view every request: - comes from `10.0.0.10`, so `HttpContext.Connection.RemoteIpAddress` is the balancer, not the skier; - arrived over `http`, so `HttpContext.Request.Scheme` is `http` and `Request.IsHttps` is `false`. ## Why links, redirects and logs break Much of the framework reads those two values: - **Absolute URLs** built by `LinkGenerator.GetUriByName(httpContext, ...)` and similar overloads take the scheme and host from the request, so a password-reset or payment-return link reads `http://shop.example/...`. - **`UseHttpsRedirection`** sees `http`, redirects to `https://`, the balancer forwards that request as `http` again, and the browser loops. - **OpenID Connect** builds its `redirect_uri` from the request, so the identity provider is asked to return to an `http://` address it does not have registered. - **Cookies** whose `CookieSecurePolicy` is `SameAsRequest` are issued without the `Secure` flag. - **Logs, rate limiting and audit trails** keyed on the client IP collapse every skier into one client: the balancer. ## The headers a proxy sends, and what the middleware rewrites Proxies record what they hid in conventional headers. The **forwarded headers middleware** (`ForwardedHeadersMiddleware`, added with `app.UseForwardedHeaders()`) copies them onto `HttpContext`: | Header | Flag in `ForwardedHeaders` | Overwrites | Old value kept in | |---|---|---|---| | `X-Forwarded-For` | `XForwardedFor` | `Connection.RemoteIpAddress` / `RemotePort` | `X-Original-For` | | `X-Forwarded-Proto` | `XForwardedProto` | `Request.Scheme` | `X-Original-Proto` | | `X-Forwarded-Host` | `XForwardedHost` | `Request.Host` | `X-Original-Host` | | `X-Forwarded-Prefix` | `XForwardedPrefix` | `Request.PathBase` | `X-Original-Prefix` | The values it consumes are removed from the `X-Forwarded-*` header, so whatever remains there was not trusted. ## Turning it on correctly ```csharp builder.Services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownProxies.Add(IPAddress.Parse("10.0.0.10")); }); var app = builder.Build(); app.UseForwardedHeaders(); ``` Four rules decide whether this works: 1. **`ForwardedHeaders` defaults to `ForwardedHeaders.None`.** The parameterless `UseForwardedHeaders()` reads `IOptions<ForwardedHeadersOptions>`; if nothing set the flags, the middleware runs and changes nothing. 2. **The sender must be trusted.** `KnownProxies` starts as `::1` only and `KnownIPNetworks` as `127.0.0.0/8` only. A balancer at `10.0.0.10` is unknown until you add it, and the middleware ignores headers from an unknown sender. 3. **Only one hop is read by default.** `ForwardLimit` is `1`, so the rightmost `X-Forwarded-For` entry wins; a chain of proxies needs more (a separate question). 4. **It must run before the consumers.** Anything that read the scheme or the IP earlier in the pipeline saw the balancer's values. Nothing in `WebApplication.CreateBuilder` adds this middleware for you, with two exceptions: out-of-process IIS hosting through the ASP.NET Core Module configures it, and the `ASPNETCORE_FORWARDEDHEADERS_ENABLED` environment variable switches on a permissive preset. ## Checking that it works - Log `RemoteIpAddress` and `Scheme` once after the middleware; the skier's address and `https` should appear. - Set the `Microsoft.AspNetCore.HttpOverrides` log category to `Debug`: an untrusted sender is logged as `Unknown proxy:` followed by its address and port, which is the usual reason nothing changed. - An `X-Original-For` header on the request proves the middleware applied a value. ## In one sentence The proxy hides the client and the scheme; `UseForwardedHeaders`, with the right flags and the proxy in its trust lists, puts them back before the rest of the app reads them.

  • Why does a bare app.UseForwardedHeaders() leave RemoteIpAddress unchanged?
    Because `ForwardedHeadersOptions.ForwardedHeaders` defaults to `ForwardedHeaders.None`. The middleware is in the pipeline but has been told to process no header. Set the flags through `Configure<ForwardedHeadersOptions>` or pass an options instance to `UseForwardedHeaders(options)`; and check the sender is in `KnownProxies` or `KnownIPNetworks`, otherwise it is ignored anyway.
  • After the middleware runs, where can you still see the address the connection really came from?
    In the `X-Original-For` request header, which the middleware writes before replacing `Connection.RemoteIpAddress`. Likewise `X-Original-Proto`, `X-Original-Host` and `X-Original-Prefix` hold the replaced scheme, host and path base. The names come from `ForwardedHeadersOptions.OriginalForHeaderName` and its siblings, so they can be changed.
  • Why does UseHttpsRedirection loop behind a TLS-terminating balancer when forwarded headers are not applied?
    It sees `Request.Scheme == "http"` and answers with a redirect to `https://`. The browser follows it, the balancer terminates TLS and forwards plain HTTP again, and the middleware redirects again. Applying `X-Forwarded-Proto` before it makes the scheme `https`, so the redirect never fires.

A hotel concierge forwards guests' letters in his own envelope. Unless the mailroom opens the envelope and reads the guest's name on the inner note, every reply goes to the concierge; it should also only trust envelopes from its own concierge.

  • Kestrel reads X-Forwarded-For on its own, so no middleware is needed.
  • A bare app.UseForwardedHeaders() processes every X-Forwarded-* header by default.
  • UseCertificateForwarding is what restores the client IP and scheme.
  • Read the first X-Forwarded-For value in each handler instead.
  • Setting app.Urls to an https:// address fixes the http:// links.
open as a page

In ASP.NET Core, what exactly does setting ASPNETCORE_FORWARDEDHEADERS_ENABLED=true configure, and when is it unsafe to use?

level: middleimportance: should knowfreq 28%

basics

~20 s

It adds UseForwardedHeaders at the very start of the pipeline, processes X-Forwarded-For and X-Forwarded-Proto, and clears KnownProxies and KnownIPNetworks so every sender is trusted. That is unsafe whenever clients can reach Kestrel without passing the proxy.

open as a page

In ASP.NET Core 10, which senders does the forwarded headers middleware trust by default, and how do you trust a load balancer subnet without KnownNetworks?

level: middleimportance: should knowfreq 45%

basics

~20 s

Only loopback senders: KnownProxies holds ::1 and KnownIPNetworks holds 127.0.0.0/8, so headers from a balancer elsewhere are ignored. Add its address to KnownProxies or its subnet, as a System.Net.IPNetwork, to KnownIPNetworks; KnownNetworks is obsolete in 10 (ASPDEPR005).

open as a page

When a proxy publishes an ASP.NET Core app under /lifts, how do UsePathBase and X-Forwarded-Prefix keep routing and generated links correct?

level: middleimportance: should knowfreq 35%

basics

~20 s

If the proxy forwards /lifts/..., UsePathBase("/lifts") moves the prefix from Request.Path to Request.PathBase so routes match and links include it. If the proxy strips it, enable XForwardedPrefix so X-Forwarded-Prefix sets PathBase from a trusted proxy.

open as a page

Behind a CDN and a load balancer, how do ASP.NET Core's ForwardLimit and trust lists pick the X-Forwarded-For entry that becomes RemoteIpAddress, and how can it be spoofed?

level: seniorimportance: should knowfreq 35%

basics

~20 s

The middleware reads X-Forwarded-For right to left, one entry per hop, while the current sender is trusted and ForwardLimit (default 1) allows. Two proxies need ForwardLimit 2 and both trusted; empty trust lists with no limit let a forged leftmost entry win.

open as a page