HTTPS redirection, HSTS and preload in ASP.NET Core, the API exception, and making them work correctly behind proxies and TLS-terminating load balancers.
TLS encrypts and authenticates the connection; HTTPS is HTTP over TLS. In ASP.NET Core, UseHttpsRedirection redirects plain-HTTP requests to HTTPS, and UseHsts adds the Strict-Transport-Security header so the browser refuses to use HTTP for that host for max-age (30 days by default), closing the first-request downgrade window after the first visit. Preload goes further: the domain is baked into browsers, so even the first visit is HTTPS — but it requires a year-long max-age, includeSubDomains, and is slow to undo.
For APIs, don't depend on redirects: non-browser clients ignore HSTS and may already have sent a token over HTTP, so refuse HTTP instead. Behind a proxy, run UseForwardedHeaders first or the app thinks every request is HTTP and loops.
"TLS gives you confidentiality, integrity and server authentication on the connection, and HTTPS is just HTTP over TLS. The problem HSTS solves is the first hop: if a user types
example.com.au, the browser starts on HTTP, and an attacker on hotel Wi-Fi can intercept that request before the redirect happens. With HSTS the server sendsStrict-Transport-Security: max-age=..., and from then on the browser rewrites every request to HTTPS internally and won't let the user click through a certificate error.In ASP.NET Core,
UseHttpsRedirectionhandles the redirect andUseHstsadds the header. The template only enables HSTS outside Development, and the middleware skips localhost so you don't poison your own browser. The default max-age is 30 days; in production I'd raise it once I'm confident, and only addincludeSubDomainsand preload after checking every subdomain serves HTTPS, because preload is effectively permanent for months.Two things trip people up. First, APIs: an HTTP client like
HttpClientor a mobile app ignores HSTS, and by the time it follows a redirect it has already sent the bearer token in clear text. So for APIs I don't listen on HTTP at all, or return 400, rather than redirect. Second, proxies: in App Service, Front Door or Kubernetes ingress, TLS terminates at the proxy and Kestrel sees HTTP. WithoutUseForwardedHeadersreadingX-Forwarded-Proto, the app redirects to HTTPS forever. The mistake I see is fixing that withForwardLimit = nulland trusting every proxy, which lets anyone spoof the client IP and scheme. HSTS is cheap, but undoing a bad preload is not."
| Piece | What it does | ASP.NET Core API |
|---|---|---|
| TLS | Encrypts and authenticates the connection | Kestrel ConfigureHttpsDefaults, platform settings |
| HTTPS redirection | 307/308 from http:// to https:// |
AddHttpsRedirection, UseHttpsRedirection |
| HSTS | Browser-enforced HTTPS for max-age |
AddHsts, UseHsts |
| Preload | Browser ships with your domain as HTTPS-only | options.Preload = true + hstspreload.org |
| Forwarded headers | Restores the original scheme and client IP | UseForwardedHeaders, ForwardedHeadersOptions |
| Concern | Browser app | API |
|---|---|---|
| Redirect HTTP to HTTPS | Yes | No: refuse HTTP (close port 80 or 400) |
| HSTS | Yes, ramp up max-age | Harmless but ignored by most clients |
| Credential leak on first request | Cookies marked Secure aren't sent over HTTP |
Bearer token already sent before the redirect |
| Stage | Header |
|---|---|
| Start | max-age=300 |
| Confident | max-age=2592000 (30 days) |
| Production steady | max-age=31536000; includeSubDomains |
| Preload (optional) | max-age=63072000; includeSubDomains; preload |
On App Service with Front Door, a common incident after moving TLS termination to the edge is an infinite 307 loop on every page: Kestrel sees http, redirects, Front Door forwards over HTTP again. Adding UseForwardedHeaders with XForwardedProto and the proxy's known network, before UseHttpsRedirection, fixes it with a one-line change; the same fix also corrects the client IP in logs, which had shown the proxy's address for 100% of requests.
Checks that the candidate understands what each control protects against, how ASP.NET Core implements it, and the real-world proxy and API pitfalls.
Green flags
UseForwardedHeaders first and restricts trusted proxiesRed flags
User types example.com.au
|
v
http://example.com.au ---> attacker on the network can answer here (SSL stripping)
|
v 301/307
https://example.com.au
HSTS removes the vulnerable step for every visit after the first. Preload removes it for the first visit too, because the browser ships with a list of HTTPS-only domains.
When a browser receives Strict-Transport-Security over HTTPS (it ignores the header over HTTP), it stores the host and expiry. For subsequent requests it performs an internal 307 to HTTPS before any network traffic, and it turns certificate warnings into hard failures with no 'proceed anyway'. includeSubDomains applies the rule to every subdomain, which is why an internal http://intranet.example.com.au can break after you enable it.
HttpsRedirectionMiddleware finds the HTTPS port from HttpsRedirectionOptions.HttpsPort, ASPNETCORE_HTTPS_PORT/ASPNETCORE_HTTPS_PORTS, or the server's bound addresses. If it can't determine one, it logs a warning and does not redirect.RedirectStatusCode = 308 in production so clients cache it.HstsMiddleware adds the header only on HTTPS requests and skips hosts in ExcludedHosts (localhost, 127.0.0.1, [::1] by default).Client --HTTPS--> Front Door / ingress --HTTP--> Kestrel
adds X-Forwarded-For, X-Forwarded-Proto
ForwardedHeadersMiddleware rewrites HttpContext.Request.Scheme and Connection.RemoteIpAddress from those headers, but only when the immediate sender is in KnownProxies/KnownNetworks (loopback by default). In containers the proxy is rarely loopback, so you must add its network, or for platforms that guarantee only the proxy can reach you, clear the lists deliberately. Setting ASPNETCORE_FORWARDEDHEADERS_ENABLED=true enables a permissive configuration for platforms such as App Service on Linux. Order matters: forwarded headers must run before HTTPS redirection, HSTS, authentication and anything that builds absolute URLs (OIDC redirect URIs are a classic victim).
Kestrel uses the operating system's TLS stack (SChannel on Windows, OpenSSL on Linux) and by default lets the OS choose protocols, which today means TLS 1.2 and 1.3. In Azure you set the minimum at the edge: App Service 'Minimum TLS version', Front Door TLS policy, Application Gateway SSL policy. Pin to TLS 1.2 minimum; TLS 1.0/1.1 are deprecated (RFC 8996). Don't hard-code SslProtocols in client code unless you have to; let the OS pick the best.
UseHsts, open it over HTTPS and check chrome://net-internals/#hsts to see the stored entry; then delete it.curl -v http://... and observe the 307, then change it to 308.UseForwardedHeaders.testssl.sh against a test endpoint and read the protocol and cipher report.Production-ready HTTPS, HSTS and forwarded-headers setup for an app behind a proxy, plus an API that refuses plain HTTP instead of redirecting.
using System.Net;
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(o =>
{
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
// Trust only the ingress subnet; otherwise anyone can spoof scheme and client IP
o.KnownNetworks.Add(new Microsoft.AspNetCore.HttpOverrides.IPNetwork(IPAddress.Parse("10.240.0.0"), 16));
});
builder.Services.AddHsts(o =>
{
o.MaxAge = TimeSpan.FromDays(365);
o.IncludeSubDomains = true; // only after every subdomain serves HTTPS
o.Preload = false; // preload is a separate, hard-to-reverse decision
});
builder.Services.AddHttpsRedirection(o => o.RedirectStatusCode = StatusCodes.Status308PermanentRedirect);
var app = builder.Build();
app.UseForwardedHeaders(); // must be first: fixes Request.Scheme before anything reads it
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection(); // browser routes
// API routes: refuse HTTP rather than redirect, so tokens are never followed over a redirect
var api = app.MapGroup("/api").AddEndpointFilter(async (ctx, next) =>
ctx.HttpContext.Request.IsHttps
? await next(ctx)
: Results.Problem("HTTPS is required.", statusCode: StatusCodes.Status400BadRequest));
api.MapGet("/ping", () => Results.Ok("pong"));
app.Run();
# Verify
curl -sI https://localhost:5001/ | grep -i strict-transport-security
curl -sI http://localhost:5000/ # expect 308 with Location: https://...
localhost to HTTPS and breaks every other local app. Instead: keep the template's !IsDevelopment() guard; the middleware also excludes localhost by default.UseForwardedHeaders after UseHttpsRedirection. Why it is wrong: the redirect middleware sees http and loops forever behind a TLS-terminating proxy. Instead: call it first in the pipeline.KnownProxies and KnownNetworks without thinking. Why it is wrong: anyone who can reach Kestrel can spoof the client IP and scheme, defeating IP rate limits and audit logs. Instead: trust the specific proxy network, or clear only when the platform guarantees only the proxy can reach you.SslProtocols.Tls12 in code. Why it is wrong: it blocks TLS 1.3 when the OS supports it. Instead: let the OS choose and set the minimum at the platform edge.The senior point is that HSTS is a browser control and redirection is a convenience; neither protects non-browser clients, and both are easy to get wrong behind proxies. Without HSTS, a user on hostile Wi-Fi who types a bare domain can be SSL-stripped: a man-in-the-middle answers the HTTP request, proxies the real site over HTTPS, and reads every cookie and password in between.
I treat TLS termination location as an architectural decision. Terminating at Front Door or the ingress simplifies certificates and enables a WAF, but it means the hop from proxy to app is plain HTTP unless you re-encrypt; that hop is inside your network, so whether it is acceptable depends on your threat model and obligations (ISM controls for government, PCI DSS for card data usually push you to re-encrypt). It also decides where forwarded headers must be trusted and which component sends HSTS (if the proxy rewrites responses, set the header once, in one place). Staging should mirror production here: an HSTS or proxy misconfiguration that only appears in production is a classic Friday incident.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Redirect + HSTS | Browser-facing sites | Low | APIs used by non-browser clients |
| Refuse HTTP entirely | APIs, internal services | Low | Public sites where users type bare domains |
| HSTS preload | Mature public domains, banks, government | Hard to reverse | Domains with legacy HTTP subdomains |
| TLS terminated at the edge only | Most web apps behind a WAF | Plain HTTP on the internal hop | Regulated data, zero-trust networks |
| End-to-end TLS (edge and proxy to app) | Regulated data, zero-trust networks | Certificate management in the cluster | Simple single-host apps |
Measure: SSL Labs grade, percentage of requests arriving over HTTP (should trend to zero), and alerts on certificate expiry.
HTTPS is HTTP inside TLS. TLS gives confidentiality (encryption), integrity (tamper detection) and server authentication (certificates).
TLS 1.3 handshake (one round trip): the client sends supported ciphers, a key share, SNI (hostname) and ALPN (h2); the server replies with its key share, certificate chain and a signature proving it owns the private key. Both derive session keys via ECDHE (forward secrecy).
The client validates: chain to a trusted root, not expired, hostname matches the SAN, and optionally revocation.
For "remote certificate is invalid": read the SslPolicyErrors / chain status, inspect with openssl s_client -showcerts, then fix the real cause (expired cert, missing intermediate, wrong hostname, or a private/corporate root CA not trusted in the container). Never return true from ServerCertificateCustomValidationCallback in production.
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.
Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.
Last updated 23 Nov 2026.