Configuring Strict-Transport-Security

There are five configuration options:

  • max-age is a TimeSpan (see TimeSpan.Parse)
  • includeSubdomains adds includeSubDomains in the header, defaults to false
  • preload adds the preload directive, defaults to false. Max-age must be at least 18 weeks, and includeSubdomains must be enabled to use the preload directive. See the Chromium HSTS docs for details.
  • httpsOnly ensures that the HSTS header is set over secure connections only, defaults to true.
  • upgradeInsecureRequests sets the HSTS header only for UAs that supports Upgrade Insecure Requests. This setting cannot be combined with preload.

Note

upgradeInsecureRequests is intended to be used in combination with the Upgrade Insecure Requests CSP directive.

Configuration Resulting header
max-age=”00:00:00” Strict-Transport-Security: max-age=0
max-age=”12:00:00” Strict-Transport-Security: max-age=43200
max-age=”365” includeSubdomains=”true” Strict-Transport-Security: max-age=31536000; includeSubDomains
max-age=”365” includeSubdomains=”true” preload=”true” Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

Register the middleware in the startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseHsts(options => options.MaxAge(days: 30).IncludeSubdomains());
    //app.UseHsts(options => options.MaxAge(days:365).IncludeSubdomains().Preload());
    //app.UseHsts(options => options.MaxAge(days:365).UpgradeInsecureRequests());

    app.UseStaticFiles();

    app.UseMvc(...);
}