skip to content

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%

answer

  1. a promise you cannot recall
  2. default max-age=2592000, nothing else
  3. start small, then raise MaxAge
  4. Preload only appends '; preload'
  5. ExcludedHosts: exact names, loopback by default

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.

solid answer

~40 s

`AddHsts(o => ...)` configures `HstsOptions`, from which `HstsMiddleware` builds one header string at startup. Defaults are `MaxAge` 30 days, `IncludeSubDomains` and `Preload` off, and `ExcludedHosts` holding `localhost`, `127.0.0.1` and `[::1]`. For a first rollout the docs advise a `MaxAge` of hours to at most a day, so a broken certificate or an HTTP-only dependency can be backed out, then raising it, typically to a year. `IncludeSubDomains` extends the policy to every subdomain of the host, so turn it on only after checking that each one serves HTTPS. `Preload = true` only appends `; preload`; getting into browsers' preload lists is a separate submission with its own rules and is slow to reverse. `ExcludedHosts` matches whole host names case-insensitively, without wildcards, and `Add` keeps the loopback defaults.

code

csharp · 19 lines
csharp
if (!builder.Environment.IsDevelopment())
{
    builder.Services.AddHsts(options =>
    {
        options.MaxAge = TimeSpan.FromHours(1);   // raise later: days, then 365
        options.IncludeSubDomains = false;        // only after every subdomain serves HTTPS
        options.Preload = false;                  // only with a deliberate preload submission
        options.ExcludedHosts.Add("staging.pharmacy.example");
    });
}

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();

go deeper

for a junior

Know the four HstsOptions and their defaults: 30 days, no includeSubDomains, no preload, loopback hosts excluded.

for a middle

Explain how the header string is built from the options, that it is fixed at startup, and how ExcludedHosts matching works.

for a senior

Plan a staged rollout with a short MaxAge first, audit subdomains before IncludeSubDomains, treat Preload as a separate commitment, and know how to roll back with max-age=0.

for a principal

Own the organisation-wide HSTS decision: which domains may use includeSubDomains or preload, who signs off, and how the edge and apps avoid conflicting headers.

## What `HstsOptions` controls `builder.Services.AddHsts(options => ...)` configures `HstsOptions` in `Microsoft.AspNetCore.HttpsPolicy`. `HstsMiddleware` reads the options **once, when it is constructed**, and builds a single `Strict-Transport-Security` value that it writes on every eligible response: | Option | Default | Effect on the header | |---|---|---| | `MaxAge` | `TimeSpan.FromDays(30)` | `max-age=` in whole seconds (fractions are dropped) | | `IncludeSubDomains` | `false` | appends `; includeSubDomains` | | `Preload` | `false` | appends `; preload` | | `ExcludedHosts` | `localhost`, `127.0.0.1`, `[::1]` | hosts that get no header at all | With every option set, the value looks like `max-age=31536000; includeSubDomains; preload`. Because the string is fixed at startup, changing these options needs a restart. ## A staged rollout for the refill site 1. **Enable HTTPS redirection and confirm every page, asset and callback works over HTTPS.** HSTS cannot fix mixed content or an HTTP-only integration; it only makes the browser refuse HTTP. 2. **Ship HSTS with a short `MaxAge`**, for example `TimeSpan.FromHours(1)`, which the ASP.NET Core docs recommend for a first deployment, keeping it to a day at most. If something breaks, removing HSTS clears returning browsers within that window. 3. **Raise `MaxAge`** in steps, to a week, then a month, then a year (`TimeSpan.FromDays(365)`), once monitoring shows no HTTP-only traffic. 4. **Decide on `IncludeSubDomains`** only after inventorying subdomains: an internal tool or an old marketing host on plain HTTP becomes unreachable in browsers that saw the header. 5. **Decide on `Preload`** last, and only together with a deliberate submission to the browsers' preload lists. Setting the flag submits nothing; the submission process and its requirements are outside ASP.NET Core, and leaving a preload list takes far longer than setting `max-age=0`. ## Using `ExcludedHosts` correctly - Matching is an **exact, case-insensitive comparison** with the request's host name (the port is not part of it). There are no wildcard patterns, so `*.pharmacy.example` excludes nothing. - `ExcludedHosts` is a list initialised with the loopback names. `options.ExcludedHosts.Add("staging.pharmacy.example")` keeps them; `Clear()` removes them, after which a developer who enables HSTS locally would pin `localhost` in their browser. - Excluding a host stops ASP.NET Core from *sending* the header there; it cannot remove a policy a browser already stored for a parent domain with `includeSubDomains`. ## Where the header should come from - If a reverse proxy, CDN or IIS already writes HSTS, configure it in one place only, so two components cannot disagree about `max-age`. - The middleware writes the header only on HTTPS requests as the app sees them. Behind a TLS-terminating proxy the app sees HTTP unless forwarded headers are processed, and `UseHsts` silently sends nothing. - Keep `UseHsts` out of Development, as the templates do; the loopback exclusions protect `localhost`, not custom local host names. ## Rolling back To withdraw a policy, keep serving HTTPS and send `MaxAge = TimeSpan.Zero` (`max-age=0`) until browsers that cached the old value have revisited. Simply removing `UseHsts` leaves every browser that saw the long `max-age` enforcing it until it expires. ## Checking what is actually sent - Request the site over HTTPS with `curl -sI https://refills.pharmacy.example/` and read the `Strict-Transport-Security` line; the same request over `http://` should show only the redirect and no HSTS header. - Request an excluded host and confirm the header is absent. - After each `MaxAge` change, confirm the new value appears only after a restart, since the middleware built its header string when the app started.

  • Why does ASP.NET Core's UseHsts send nothing for an app behind a TLS-terminating load balancer?
    `HstsMiddleware` adds the header only when `Request.IsHttps` is true. Behind a proxy that terminates TLS, the app receives plain HTTP unless forwarded headers restore the original scheme, so every response is treated as insecure and skipped. Either process forwarded headers so the app sees `https`, or let the proxy write the header.
  • How do you withdraw an HSTS policy that ASP.NET Core has been sending with a one-year max-age?
    Keep HTTPS working and change `HstsOptions.MaxAge` to `TimeSpan.Zero`, so returning browsers receive `max-age=0` and drop the stored policy. Removing `UseHsts` instead leaves every browser that cached the year-long value enforcing it until it expires.

  • Setting HstsOptions.Preload = true submits the site to the browsers' preload list.
  • ExcludedHosts accepts wildcard patterns such as *.pharmacy.example.
  • Adding a host to ExcludedHosts removes localhost from the defaults.
  • A first HSTS rollout should start with a one-year MaxAge.
  • IncludeSubDomains is enabled by default in ASP.NET Core.