How to enforce SSL in ASP.Net Core

Take advantage of HTTPS and the HSTS security enhancement to encrypt web client and server communications in your ASP.Net Core applications

How to enforce SSL in ASP.Net Core
Thinkstock

Secure Sockets Layer—SSL for short—is a standard security protocol that is used to encrypt communications between a web server and a web browser. SSL is important! Without it, information that is exchanged between a server and a client is sent in plain text, so would be readable by any hacker who is able to capture the data.

SSL ensures that information sent between server and client is always encrypted. Even if captured, your sensitive data—user name, password, credit card details, etc.—will remain unreadable to anyone lacking the SSL certificate and encryption key shared by the server and client during the communications session. 

In this article we will look at how we can work with SSL in ASP.Net Core. We will use a new middleware component, UseHttpsRedirection, to redirect all HTTP requests to HTTPS. We will also take advantage of HSTS (HTTP Strict Transport Security), an optional security enhancement, to further strengthen the security of web connections. Support for the new middleware and the HSTS enhancement was introduced in ASP.Net Core 2.1 to enforce the use of HTTPS by clients in a connection.

Create an ASP.Net Core Web API project

First off, let’s create an ASP.NET Core project and install the necessary packages. If Visual Studio 2017 is up and running in your system, follow the steps outlined below to create an ASP.Net Core Web API project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. Select “API” in the “New .Net Core Web Application…” window.
  7. Select the version ASP.Net Core 2.1 or later from the drop-down list at the top of the window.
  8. Uncheck “Enable Docker Support” and select “No Authentication” as we won’t be using either of these here.
  9. Ensure that the “Configure for HTTPS” box is checked. 
  10. Click OK.

This will create a new ASP.Net Core application in Visual Studio with SSL enabled. The new default templates will have the necessary middleware components already added in the Startup.cs file as shown in the code snippet below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        // Write your own custom code to configure the middleware
    }
    else
    {
        app.UseHsts();
    }
    app.UseHttpsRedirection();
}

Here is a modified version of the default Configure method that was generated. The following code snippet illustrates how the UseDeveloperExceptionPage method has been used to capture exceptions from the pipeline and then generate HTML error responses accordingly.

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

When running your application in a production environment, you will want to configure the middleware to redirect all HTTP requests to HTTPS. The following section demonstrates how the AddHttpsRedirection middleware can be customized to achieve this.

Redirect HTTP requests to HTTPS in ASP.Net Core

Open the Startup.cs file and add the following code in the ConfigureServices method. Note how the AddHttpsRedirection method has been used to configure the middleware options. The HTTPS port has been set to 5001 here; the default is 443.

    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 5001;
    });

Use HSTS in ASP.Net Core for enhanced security

HTTP Strict Transport Security is an opt-in security mechanism and an HTTP/2 feature. HSTS is specified using a special response header and can be used to protect websites against man-in-the middle attacks. HSTS ensures that the web browser caches the certificate for specific host headers and for a specific time duration.

However, because HSTS is enforced by the client, there are certain limitations. The client should support HSTS and you need at least one successful HTTPS request, which is needed to establish the HSTS policy. The following code snippet illustrates how HSTS is configured in the ConfigureServices method.

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

When you run your project, you will be prompted to trust the self-signed certificate that IIS Express (if you are using IIS Express) has generated. If you click on “Yes,” you will be prompted to install the certificate. Click “Yes” again to install the certificate. And that’s it! When you run the application in your web browser you will observe HTTPS on the URL. For production, you should buy a valid trusted certificate from a reputable certificate authority and then install it from the Windows certificate store.

HTTPS not only encrypts the traffic between a server and a client, it also prevents others from modifying the content. HSTS is a web security policy mechanism that is used to ensure that web browsers interact with the web servers only via secure HTTPS connections and never via an insecure one. I will talk more about ASP.Net Core security in upcoming posts here.

Copyright © 2018 IDG Communications, Inc.