What is HSTS (HTTP Strict Transport Security), and how does UseHsts() in ASP.NET Core implement it?
Short answer
HSTS is a response header (Strict-Transport-Security) instructing browsers to automatically convert any future request to the site into HTTPS internally, without even attempting a plain HTTP connection first -- this closes the vulnerability window that plain HTTP-to-HTTPS…
Advertisement
AModel answer
HSTS is a response header (Strict-Transport-Security) instructing browsers to automatically convert any future request to the site into HTTPS internally, without even attempting a plain HTTP connection first -- this closes the vulnerability window that plain HTTP-to-HTTPS redirection alone leaves open (the very first request in a session is still sent over unencrypted HTTP before the redirect happens), since after the first HSTS-header response, the browser enforces HTTPS-only on its own for the specified duration (max-age).
builder.Services.AddHsts(options => {
options.MaxAge = TimeSpan.FromDays(365);
options.IncludeSubDomains = true;
options.Preload = true;
});
var app = builder.Build();
if (!app.Environment.IsDevelopment()) {
app.UseHsts(); // adds Strict-Transport-Security header to responses
}Real-world example
A financial services site configures HSTS with a full year max-age and IncludeSubDomains, ensuring that once a user's browser has visited the site once over HTTPS, it will never again attempt a plain HTTP connection to that domain or any of its subdomains for the following year, even if a user explicitly types http://.
Likely follow-ups
- What is HSTS preloading, and how does submitting to the browser preload list eliminate the first-visit vulnerability window entirely?
- What risk does a very long max-age create if you ever need to revert to HTTP temporarily?
Related topics