Setting up HTTPS in Asp.net core 1.1

By | Mar 24, 2018

Securing a website with HTTPS in Asp.net core is a bit different than with normal asp.net in IIS. In this post I will show to configure asp.net core so that it uses HTTPS.

How to apply HTTPS in Asp.net core 1.1

I have been working on an asp.net core site and will be showing some of the code snippets and steps needed.

  1. We start in the program.cs Main method where we need to load the JSON file which will contain the certificate information.
    var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("hostingOptions.json", true, true)
    .Build();
    
    • Define a configuration builder.
    • Specify the base path to use. In this example it will be the current directory.
    • Specify that we are adding a JSON file, in this example it is called hostingOptions.js. The file is optional and the application should be reloaded if the file changes. The JSON files not exist at this point.
  2.  Next add a JSON file into the root of the website and call it “hostingOptions.json” with the following structure
    • The server.urls represents the secure url of the website.
    • certificate.location is where the pfx file can be found in relation to the website.
    • certificate.password is obvious – its the password for the pfx.
  3. Next create the Certificates folder and copy your certificate pfx file into it.
  4. Back to the program.cs Main method. After the configuration builder, load the certificate with the following syntax.
    X509Certificate2 siteCertificate = new X509Certificate2(config["certificate.location"], config["certificate.password"]);
    
  5. Now we are ready to configure the host. I am using Kestrel.
    var host = new WebHostBuilder()
    .UseKestrel(options =>
    {
    options.UseHttps(siteCertificate);
    })
    .UseConfiguration(config)
    .UseContentRoot(Directory.GetCurrentDirectory())
    //.UseIISIntegration()
    .UseStartup<Startup>()
    .UseApplicationInsights()
    .Build();
    
    • Instruct the web host to use HTTP and assign the certificate to use.

The completed method will look like this.

Here is another article, If you are looking for more information related to the security of Asp.net core

0 0 vote
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments