ASPNET Core How to Add HSTS Security Headers

Today in this article, we shall see in ASP.NET Core how to Add HSTS Security Headers to Web/API applications.

Today we will cover the following aspects in this article,

Most of these headers once added to response headers use in-built browser features to protect your data and communication over the network.

Types of Security Headers

Below are the various security headers which can be used in various contexts as needed.

  • HTTP Strict Transport Security (HSTS)

  • X-Frame-Options

  • X-Content-Type-Options

  • Content-Security-Policy

  • X-XSS-Protection

Enable HTTP Strict Transport Security (HSTS) in .NET Core

What is HSTS (HTTP Strict Transport Security )

The HTTP Strict-Transport-Security i.e. HSTS informs browsers that the application or site should only be accessed via HTTPS protocol. This also indicates any access if done via HTTP should automatically be converted to HTTPS.

Characteristics and guidelines

This header provides below characteristics (but are not limited to), and guidelines for building secured applications

  • It allows the websites or API owners to declare their website/API is accessible only via secure connections.

  • It allows the user of the website to interact with the website/API in secure connections.

  • It protects the websites against protocol downgrade attacks.

  • It protects the website’s action against cookie hijacking.

  • It allows interaction with HTTPS connections only.

  • The server implements Strict-Transport-Security by adding a header over an HTTPS connection.

  • HSTS Headers are ingonred over HTTP.

  • The browser restricts the user from using untrusted or invalid certificates. 

  • The browser disables prompts that allow a user to temporarily trust such a certificate.

Adding HSTS in ASP.NET Core

Adding HSTS in ASP.NET Core can be achieved using the middleware component easily. We shall see both inline middleware and custom middleware techniques.

Syntax :

Strict-Transport-Security: max-age=<time>
Strict-Transport-Security: max-age=<time>; includeSubDomains
Strict-Transport-Security: max-age= <time>; preload

Directives details:

  • max-age=<expire-time> – (Required) – Time in seconds. This is the duration of time the browser remembers that a site is only to be accessed using HTTPS.

  • includeSubDomains – (Optional) – Enables include SubDomain parameter of the Strict-Transport-Security header.

  • preload- (Optional) – preload is supported by web browsers but is not part of the RFC specification yet.

Example:

 content-type: application/json; charset=utf-8 
 date: Sun24 Jan 2021 00:01:09 GMT 
 server: Microsoft-IIS/10.0 
 strict-transport-security: max-age=31536000 ; includeSubDomains;preload
 x-powered-by: ASP.NET 

In the above example,

  • max-age is set to 1 year
  • suffixed with preload, (necessary for inclusion in all major web browsers’ HSTS preload lists, like Chromium, Edge, and Firefox.)

Strict-Transport-Security can be added to ASP.NET Core API programmatically using the middleware approach which is discussed below in more detail.

The below code helps you add the HSTS middleware component to the API pipeline as below,

Step 1

In the ConfigureServices, using AddHsts which adds the required HSTS services

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

            services.AddHsts(options =>
            {
                options.Preload = true;
                options.IncludeSubDomains = true;
                options.MaxAge = TimeSpan.FromDays(365);
            });

..

..

       }

Step 2

In the Configure method add UseHsts middleware for using HSTS, which adds the Strict-Transport-Security header.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();

            }
..
..
..
      }

The default HSTS value is 30 days if not specified.

With the above basic steps, the ASP.NET Core application hosted on IIS or Clouds should be able to send HTTP Strict Transport Security Protocol (HSTS) headers to clients.

Failed to determine the https port for redirectASPNET Core How to Add HSTS

Using PostMan,

enforce security headers HSTS in ASPNET Core

UseHttpsRedirection middleware

As per Microsoft guidelines, the production ASP.NET Core app should also use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.

This can be done by adding UseHttpsRedirection a Redirection middleware in the API.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

Apps deployed with a reverse proxy and capable of handling HTTPS redirection don’t need to use HTTPS Redirection Middleware.

For more information please refer to Microsoft guidelines

Redirection Middleware will need a port to be available to redirect an HTTP request to HTTPS else error “Failed to determine the HTTPS port for the redirect.” will be thrown.

Additional Guidelines

  • Do not use HSTS in a local development environment. HSTS setting is recommended to be used in a Prod environment.

  • HSTS settings are cached by the browser.

  • HSTS settings are ignored over an HTTP connection.

  • HSTS excludes the below loopback host. Example
    • localhost
    • 127.0.0.1
    • [::1]

References:

If you want to set various headers like X-Frame-Option X-Content-Type-Options Content-Security-Policy X-XSS-Protection, please visit the below article for more details,

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



4 thoughts on “ASP.NET Core How to Add HSTS Security Headers

    1. Hi Lakshmi – Kindly check if all the steps mentioned in the article are followed by you. You can very much check headers in the API route response and confirm. Also if an issue still exists, see if the warning can be classified as a false positive.

Leave a Reply

Your email address will not be published. Required fields are marked *