liveBook · Manning

X-Forwarded-Proto header

As explained in ASP.NET Core in Action, 3e

X-Forwarded-Proto is an HTTP request header that identifies the protocol used by the client for the original request to a proxy.

X-Forwarded-Proto tells an application whether the client originally used HTTP or HTTPS when connecting through a reverse proxy. This preserves protocol information that can be lost when the proxy forwards the request to the app. section 27.3.2 section 28.4.2

ASP.NET Core reads this header with ForwardedHeadersMiddleware and updates Request.Scheme and related HttpContext properties. Enable the automatically added middleware with ASPNETCORE_FORWARDEDHEADERS_ENABLED=true, or configure it manually. Place it early, before middleware such as UseHttpsRedirection or UseHsts that depends on the request scheme. section 27.3.2 section 28.4.2

Recognizing an HTTPS request behind a proxy

A request reaching the app as http://localhost with X-Forwarded-Proto: https is treated as though it originally used https://localhost. Consequently, later middleware sees the request as secure instead of redirecting it based only on the proxy-to-app connection. section 27.3.2 section 28.4.2

Listing 27.1 Configuring an app to use forwarded headers in Startup.cs
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.UseForwardedHeaders(new ForwardedHeadersOptions         #1
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor |     #2
                       ForwardedHeaders.XForwardedProto     #2
});
app.UseHttpsRedirection();                                  #3
app.UseRouting();                                           #3
app.MapGet("/", () => "Hello world!");
app.Run();

Shows a minimal ASP.NET Core pipeline that enables X-Forwarded-Proto and X-Forwarded-For handling before HTTPS redirection and routing. section 27.3.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains proxy information loss, middleware configuration, request-property updates, and pipeline ordering without detailing header trust or proxy validation.
Examples
Uses a forwarded HTTPS request to localhost and a C# middleware pipeline configured for X-Forwarded-Proto.
What it assumes
Assumes a reverse-proxy deployment and introduces how proxy forwarding changes request information and how ASP.NET Core restores it.
What you can do after
Operate/configure ASP.NET Core behind a reverse proxy so HTTPS-aware middleware receives the original request scheme.
How it connects
Connects reverse proxies, TLS termination, ForwardedHeadersMiddleware, Kestrel, HTTPS redirection, and HSTS.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.