📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do HTTPS, TLS and HSTS fit together in an ASP.NET Core app? Explain UseHttpsRedirection and UseHsts, what HSTS preload means, why APIs are handled differently from browser apps, and what changes when the app runs behind a reverse proxy or Azure Front Door.

HTTPS redirection, HSTS and preload in ASP.NET Core, the API exception, and making them work correctly behind proxies and TLS-terminating load balancers.

Intermediate Theory Intermediate aspnet-core hsts https reverse-proxy security tls

🎯 Key points

  • UseHttpsRedirection defaults to 307 (temporary); set RedirectStatusCode = 308 for permanent redirects in production
  • HSTS header tells browsers to use HTTPS only for max-age; ASP.NET Core default is 30 days
  • UseHsts excludes localhost; the template enables it in every non-Development environment, including staging
  • hstspreload.org requires max-age >= 31536000, includeSubDomains and preload; ramp up with short max-age values first
  • APIs should not rely on redirects: refuse plain HTTP so credentials are never sent in clear
  • Behind a proxy, UseForwardedHeaders (X-Forwarded-Proto) must run first or you get redirect loops
  • Restrict KnownProxies/KnownNetworks so forwarded headers can't be spoofed
  • Minimum TLS 1.2, prefer 1.3; decide where TLS terminates and whether proxy-to-app traffic is re-encrypted

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 sends Strict-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, UseHttpsRedirection handles the redirect and UseHsts adds 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 add includeSubDomains and 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 HttpClient or 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. Without UseForwardedHeaders reading X-Forwarded-Proto, the app redirects to HTTPS forever. The mistake I see is fixing that with ForwardLimit = null and trusting every proxy, which lets anyone spoof the client IP and scheme. HSTS is cheap, but undoing a bad preload is not."


The pieces

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

Browser app vs API

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

HSTS rollout

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains SSL stripping and why HSTS closes it after the first visit
  • Knows the API exception: refuse HTTP rather than redirect
  • Orders UseForwardedHeaders first and restricts trusted proxies
  • Treats preload as a deliberate, slow-to-reverse decision

Red flags

  • Thinks HTTPS redirection alone is enough
  • Fixes proxy loops by trusting all forwarded headers from anyone
  • Hard-codes old TLS versions or disables certificate validation

📚 Learn in depth

1. The downgrade problem

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.

2. What the browser does with HSTS

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.

3. How ASP.NET Core implements 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.
  • The default status code is 307 (Temporary Redirect); set 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).

4. Behind a proxy

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).

5. TLS versions and where they're set

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.

Try it yourself

  1. Run an app with UseHsts, open it over HTTPS and check chrome://net-internals/#hsts to see the stored entry; then delete it.
  2. Call the app with curl -v http://... and observe the 307, then change it to 308.
  3. Put the app behind a local YARP or nginx proxy that terminates TLS and reproduce the redirect loop; fix it with UseForwardedHeaders.
  4. Run SSL Labs or testssl.sh against a test endpoint and read the protocol and cipher report.
  5. Write an integration test that asserts the HSTS header is present on an HTTPS response in the Production environment.

💻 Code

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://...

⚠ Common mistakes

  • Mistake: Enabling HSTS in Development. Why it is wrong: the browser pins localhost to HTTPS and breaks every other local app. Instead: keep the template's !IsDevelopment() guard; the middleware also excludes localhost by default.
  • Mistake: Submitting to the preload list on day one. Why it is wrong: removal takes months to reach all browsers, and any HTTP-only subdomain breaks. Instead: ramp max-age up, inventory subdomains, then decide on preload.
  • Mistake: Relying on HTTPS redirection to protect an API. Why it is wrong: the client already sent the bearer token over HTTP before the redirect. Instead: don't listen on HTTP, or reject it with 400.
  • Mistake: Putting 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.
  • Mistake: Clearing 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.
  • Mistake: Forcing 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.
  • Mistake: Thinking HSTS sent over HTTP takes effect. Why it is wrong: browsers ignore the header on non-secure responses. Instead: make sure the first HTTPS response carries it.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the TLS handshake or certificate validation Why: Checks depth on the TLS 1.3 handshake and fixing certificate errors without disabling validation
    How to answer

    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.

  2. When: Candidate mentions redirect loops or forwarded headers behind a proxy Why: Checks they can safely configure forwarded headers and diagnose proxy issues
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    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.

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me