skip to content

HTTPS & HSTS

Forcing HTTPS in ASP.NET Core: UseHttpsRedirection, HSTS and its defaults, the development certificate, and AllowedHosts host filtering. Interviewers ask why HSTS is off in Development.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core, what do UseHttpsRedirection and UseHsts each do, and why do the web templates call UseHsts only outside Development?

level: juniorimportance: must knowfreq 64%

answer

  1. one redirects, one instructs the browser
  2. 307 Temporary Redirect by default
  3. Strict-Transport-Security: max-age=2592000
  4. header only on HTTPS responses
  5. browsers cache it, so not in Development

basics

~10 s

UseHttpsRedirection answers plain-HTTP requests with a 307 redirect to the HTTPS URL; UseHsts adds a Strict-Transport-Security header, 30 days by default, to HTTPS responses. Browsers cache HSTS, so the templates skip it in Development.

solid answer

~40 s

`UseHttpsRedirection()` adds `HttpsRedirectionMiddleware`: a request that is not HTTPS gets `307 Temporary Redirect` with a `Location` built from `https`, the same host, the HTTPS port, path and query; HTTPS requests pass through. `UseHsts()` adds `HstsMiddleware`, which on HTTPS responses only writes `Strict-Transport-Security: max-age=2592000` (30 days, no `includeSubDomains`, no `preload`) and skips `localhost`, `127.0.0.1` and `[::1]`. A returning browser then rewrites `http://` URLs for that host to `https://` itself, while the redirect still serves first visits and clients that ignore HSTS. The Razor Pages and MVC templates put `UseHsts()` inside `if (!app.Environment.IsDevelopment())` because browsers cache the policy for its whole `max-age`, which would keep forcing HTTPS on a developer's host names long after a project stopped serving it. The webapi template calls `UseHttpsRedirection()` but not `UseHsts()`.

code

http · 11 lines
http
GET /refills/42 HTTP/1.1
Host: refills.pharmacy.example

HTTP/1.1 307 Temporary Redirect
Location: https://refills.pharmacy.example/refills/42

GET /refills/42 HTTP/1.1
Host: refills.pharmacy.example

HTTP/1.1 200 OK
Strict-Transport-Security: max-age=2592000

go deeper

for a junior

Recall which middleware redirects and which writes Strict-Transport-Security, the 307 and 30-day defaults, and the Development guard in the templates.

for a middle

Explain how the redirect URL is built, which hosts HSTS skips, why HSTS appears only on HTTPS responses, and why browsers caching it rules it out in Development.

for a senior

Know when an API should refuse HTTP instead of redirecting, and when a proxy or load balancer already handles redirection and HSTS so the app should not.

for a principal

Decide where transport policy lives across many services, in each app or at the edge, and how HSTS commitments are reviewed before they are made.

## Two middlewares, two jobs ASP.NET Core splits "use HTTPS" into two independent pieces from the `Microsoft.AspNetCore.HttpsPolicy` package, which is part of the shared framework: | | `UseHttpsRedirection()` | `UseHsts()` | |---|---|---| | Middleware | `HttpsRedirectionMiddleware` | `HstsMiddleware` | | Acts on | requests that are not HTTPS | HTTPS responses only | | Effect | ends the request with a redirect | adds a response header and continues | | Default | `307 Temporary Redirect` | `max-age=2592000` (30 days) | | Options | `AddHttpsRedirection(o => ...)` | `AddHsts(o => ...)` | Neither needs its `Add*` call: both run with default options when you only call `Use*`. ## What `UseHttpsRedirection` does For each request: 1. If `Request.IsHttps` is true, it calls the next middleware. 2. Otherwise it determines the HTTPS port once for the app's lifetime; if it cannot find one it logs a warning and lets the request through unredirected. 3. It builds `https://{host}:{port}{pathBase}{path}{query}`, omitting the port when it is 443. 4. It sets the status (`307` by default, from `HttpsRedirectionOptions.RedirectStatusCode`) and the `Location` header, and ends the request. A `307` keeps the method and body, so a `POST` to `http://` is replayed as a `POST` to `https://` instead of turning into a `GET`. ## What `UseHsts` does `HstsMiddleware` builds the header value once, from `HstsOptions`, when it is constructed: - `MaxAge` defaults to **30 days** and is written in whole seconds: `max-age=2592000`. - `IncludeSubDomains` and `Preload` default to **false**, so neither directive appears. - `ExcludedHosts` defaults to **`localhost`, `127.0.0.1` and `[::1]`**, matched case-insensitively against the request's host. On each request, the header is added only when the request is HTTPS and the host is not excluded. A browser ignores the header on plain HTTP anyway, so writing it there would be pointless. ## Why the templates guard `UseHsts` The Razor Pages and MVC templates generate: ```csharp if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. app.UseHsts(); } app.UseHttpsRedirection(); ``` - **Browsers cache HSTS.** Once a browser has seen the header for a host, it upgrades every later `http://` URL for that host for the whole `max-age`, with no way for the server to take it back sooner. - On a developer machine that pins a host name for 30 days, and plain-HTTP projects on the same host name stop being reachable over HTTP from that browser. - The loopback names are already in `ExcludedHosts`, but only as exact names: a `myapp.dev.localhost` address, which .NET 10's `--localhost-tld` template option produces, or a custom name in the hosts file is not excluded. - `UseHttpsRedirection` has no such lasting effect: it answers one request at a time and uses a temporary status, so the templates leave it on in every environment. ## What the API template does differently `dotnet new webapi` calls `UseHttpsRedirection()` but **not** `UseHsts()`. HSTS is an instruction only browsers follow; mobile, desktop and server clients ignore it. The ASP.NET Core docs go further for APIs: rather than redirecting, an API that handles sensitive data should listen only on HTTPS or reject HTTP, because a client that follows a redirect has already sent its request, and any token in it, over plain HTTP. ## Turning both off `dotnet new webapp --no-https` (and the same option on the other web templates) generates neither call and no HTTPS launch profile, for services whose TLS is terminated elsewhere.

  • Does ASP.NET Core's UseHsts redirect HTTP requests to HTTPS?
    No. `HstsMiddleware` only adds `Strict-Transport-Security` to HTTPS responses and does nothing for plain HTTP. The first visit over `http://` still needs `UseHttpsRedirection` (or a proxy) to reach HTTPS; after that the browser upgrades URLs itself for the `max-age`.
  • Why does the ASP.NET Core webapi template call UseHttpsRedirection but not UseHsts?
    HSTS is a browser instruction; mobile, desktop and server clients ignore it, so for a JSON API it adds little. The docs recommend that APIs handling sensitive data listen only on HTTPS or reject HTTP outright, since a redirected client has already sent its request over plain HTTP.

A shop door with an attendant and a sign: the attendant (redirection) walks each customer arriving at the side entrance round to the front, while the sign (HSTS) tells regular customers to use the front door for the next month, and they remember it even if the sign is later removed.

  • UseHsts redirects HTTP requests to HTTPS.
  • UseHttpsRedirection sends 301 Moved Permanently by default.
  • UseHsts writes the header on plain-HTTP responses too.
  • The default HSTS max-age in ASP.NET Core is one year.
  • UseHsts does nothing unless AddHsts is called first.
open as a page

What does dotnet dev-certs https --trust do for local ASP.NET Core development, and when do you reach for --check, --clean or --export-path?

level: juniorimportance: should knowfreq 36%

basics

~20 s

The .NET SDK creates an ASP.NET Core HTTPS development certificate for localhost but does not trust it; dotnet dev-certs https --trust adds it to the trusted stores so browsers accept https://localhost. --check tests it, --clean removes it, --export-path copies it out.

open as a page

What does the AllowedHosts setting in an ASP.NET Core appsettings.json do, and how should a production app configure host filtering?

level: middleimportance: should knowfreq 38%

basics

~10 s

AllowedHosts feeds the host filtering middleware that WebApplication adds automatically: requests whose Host header is not in the semicolon-separated list get 400. The template's "*" disables it; production should list its real host names.

open as a page

How does ASP.NET Core's UseHttpsRedirection choose the redirect status and the HTTPS port, and why might it not redirect at all?

level: middleimportance: should knowfreq 44%

basics

~10 s

The status comes from HttpsRedirectionOptions.RedirectStatusCode, 307 unless you set 308. The port comes from HttpsPort, then HTTPS_PORT configuration, then the server's https address; with none, it logs a warning and does not redirect.

open as a page

Rolling HSTS out on a pharmacy refill site with ASP.NET Core, how would you set AddHsts's MaxAge, IncludeSubDomains, Preload and ExcludedHosts?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Start with a short MaxAge (hours to a day), raise it once HTTPS is stable, enable IncludeSubDomains only when every subdomain serves HTTPS, set Preload only before deliberately submitting the domain, and add exact host names to ExcludedHosts.

open as a page