Skip to content

Strict‐Transport‐Security (HSTS)

Marthijn van den Heuvel edited this page Aug 19, 2024 · 5 revisions

The HTTP Strict-Transport-Security response header (often abbreviated as HSTS) informs browsers that the site should only be accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be converted to HTTPS.

Usage

Default usage (i.e. max-age set to two years, and include subdomains):

app.UseStrictTransportSecurity();

With options:

app.UseStrictTransportSecurity(new StrictTransportSecurityHeaderOptions
{
    // MaxAge set to 0 will immediately expire the header, might be handy for testing.
    // It is not recommended for production.
    MaxAge = 0,
    IncludeSubDomains = false,
    Preload = true,
});

Localhost requests

By default, the HSTS header is not appended for localhost requests. However, when the testing library is used and the header is not found, the test wil fail. To enable HSTS for localhost requests, use:

app.UseStrictTransportSecurity(new StrictTransportSecurityHeaderOptions
{
    DisableForLocalhostRequests = false,
});

Alternatives

ASP.NET Core has built-in support for HSTS. The following code can be used to enable HSTS:

app.UseHsts();

A configuration can be provided by registering the HstsOptions class. Note the default settings are different from the default settings in this library. By default, the max-age is set to 30 days, while this library sets it to two years (which is recommended).

For more information, see: UseHsts.

References

Clone this wiki locally