Chapter 4: Configuring and Customizing HTTPS with Kestrel

In ASP.NET Core, HTTPS is on by default, and it is a first-class feature. On Windows, the certificate that is needed to enable HTTPS is loaded from the Windows certificate store. If you create a project on Linux or Mac, the certificate is loaded from a certificate file.

Even if you want to create a project to run it behind an IIS or an NGINX web server, HTTPS is enabled. Usually, you would manage the certificate on the IIS or NGINX web server in that case. Having HTTPS enabled here shouldn't be a problem, however, so don't disable it in the ASP.NET Core settings.

Managing the certificate within the ASP.NET Core application directly makes sense if you run services behind the firewall, services that are not accessible from the internet, services such as background services for a microservice-based application, or services in a self-hosted ASP.NET Core application.

There are also some scenarios on Windows where it makes sense to load the certificate from a file. This could be in an application that you will run on Docker for Windows or Linux. Personally, I like the flexible way of loading the certificate from a file.

Only two topics will be covered in this short chapter:

  • Introducing Kestrel
  • Setting up Kestrel

The topics in this chapter refer to the hosting layer of the ASP.NET Core architecture:

Figure 4.1 – The ASP.NET Core architecture

Figure 4.1 – The ASP.NET Core architecture

Technical requirements

To follow the descriptions in this chapter, you will need to create an ASP.NET Core MVC application. To do this, open your console, shell, or Bash terminal, and change to your working directory. Then, use the following command to create a new MVC application:

dotnet new mvc -n HttpSample -o HttpSample

Now, open the project in Visual Studio by double-clicking the project file, or in Visual Studio Code by typing the following command in the already-open console:

cd HttpSample

code .

All of the code samples in this chapter can be found in the GitHub repository for this book at https://github.com/PacktPublishing/Customizing-ASP.NET-Core-6.0-Second-Edition/tree/main/Chapter04.

Introducing Kestrel

Kestrel is a newly implemented HTTP server that is the hosting engine of ASP.NET Core. Every ASP.NET Core application will run on the Kestrel server. Classic ASP.NET applications (running on .NET Framework) usually run directly on the IIS. With ASP.NET Core, Microsoft was inspired by Node.js, which also ships an HTTP server called libuv. In the first version of ASP.NET Core, Microsoft also used libuv, and then it added a layer on top called Kestrel. At that time, Node.js and ASP.NET Core shared the same HTTP server.

Since the .NET Core framework has grown and .NET sockets have been implemented on it, Microsoft has built its own HTTP server based on .NET sockets and removed libuv, which was a dependency they don't own and control. Now, Kestrel is a full-featured HTTP server that runs ASP.NET Core applications.

The IIS acts as a reverse proxy that forwards the traffic to Kestrel and manages the Kestrel process. On Linux, usually NGINX is used as a reverse proxy for Kestrel.

Setting up Kestrel

As we did in the first two chapters of this book, we need to override the default WebHostBuilder a little bit to set up Kestrel. With ASP.NET Core 3.0 and later, it is possible to replace the default Kestrel base configuration with a custom configuration. This means that the Kestrel web server is configured to the host builder. Let's look at the steps to set up:

  1. You will be able to add and configure Kestrel manually simply by using it. The following code shows what happens when you call the UseKestrel() method on IwebHostBuilder. Let's now see how this fits into the CreateWebHostBuilder method:

    public class Program

    {

        public static void Main(string[] args)

        {

            CreateWebHostBuilder(args).Build().Run();

        }

        public static IHostBuilder

          CreateHostBuilder(string[] args) =>

            Host.CreateDefaultBuilder(args)

                .ConfigureWebHostDefaults(webBuilder =>

                {

                    webBuilder

                        .UseKestrel(options =>

                        {

                        })

                        .UseStartup<Startup>();

                }

    }

    The preceding code shows how the Program.cs looked until ASP.NET Core 5.0. In ASP.NET Core 6.0, the new minimal API approach is used to configure your application:

    var builder = WebApplication.CreateBuilder(args);

    builder.WebHost.UseKestrel(options =>

    {

    });

    // Add services to the container.

    builder.Services.AddControllersWithViews();

    var app = builder.Build();

    // the rest of this file is not relevant

    We'll focus on the UseKestrel() method for the rest of this chapter. The UseKestrel() method accepts an action to configure the Kestrel web server.

  2. What we actually need to do is configure the addresses and ports that the web server is listening on. For the HTTPS port, we also need to configure how the certificate should be loaded:

    builder.WebHost.UseKestrel(options =>

    {

        options.Listen(IPAddress.Loopback, 5000);

        options.Listen(IPAddress.Loopback,  5001,

          listenOptions  =>

        {

            listenOptions.UseHttps("certificate.pfx",

              "topsecret");

        });

    });

    Don't forget to add a using statement to the System.Net namespace to resolve the IPAddress.

    In this snippet, we add the addresses and ports to listen on. The configuration is defined as a secure endpoint configured to use HTTPS. The UseHttps() method is overloaded multiple times in order to load certificates from the Windows certificate store as well as from files. In this case, we will use a file called certificate.pfx located in the project folder.

  3. To create a certificate file to just play around with this configuration, open the certificate store and export the development certificate created by Visual Studio. It is located in the current user certificates under the personal certificates:

Figure 4.2 – Certificates

Right-click this entry. In the context menu, go to All Tasks and click Export. In the Certificate Export Wizard, click Next and then click Yes, export the private key, then click Next. Now, choose the .PFX format in the next screen and click Next. Here, you need to set a password. This is the exact same password you will need to use in the code, as seen in the following code example. Choose a filename and a location to store the file, and then click Next. The last screen will show a summary. Click Finish to save the certificate to a file.

For your safety

Use the following line only to play around with this configuration:

listenOptions.UseHttps("certificate.pfx", "topsecret");

To clarify why – the problem is the hardcoded password. Never, ever store a password in a code file that gets pushed to any source code repository. Ensure that you load the password from the configuration API of ASP.NET Core. Use the user secrets on your local development machine and use environment variables on a server. On Azure, use the application settings to store the passwords. Passwords will be hidden on the Azure portal UI if they are marked as passwords.

Summary

This is just a small customization, but it should help if you want to share the code between different platforms, or if you want to run your application on Docker and don't want to worry about certificate stores, and so on.

Usually, if you run your application behind a web server such as an IIS or NGINX, you don't need to care about certificates in your ASP.NET Core 6.0 application. However, if you host your application inside another application, on Docker, or without an IIS or NGINX, you will need to.

In the next chapter, we're going to talk about how to configure the hosting of ASP.NET Core web applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.192.212