Search code examples
linuxsslasp.net-coreraspberry-pi3kestrel

Load an SSL certificate from appsettings.json


I built a .NET core 2.2 application, that I am loading onto a raspberry pi. I am hosting the web service using Kestrel. On the pi, I have created a self-assigned certificate.pfx. If I hard code into the application a .UseHttps with the certificate name and password, the browser can find it.

However, if I comment it out of the code and use the appsettings.json file instead (I would like it in the appsettings.json, so clients can upload their own certificates), the redirect to Https will work, but the certificate is not loading and the page fails to connect.

This is the document I have been using to configure my appsettings.json file: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2

The certificate is located in the application folder.

Currently I have this code commented out of the application, but it does work when the code is not commented. I am hoping to set up these same settings through the appsettings.json file instead.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureKestrel((context, options) =>
                {                   
                    /*options.Listen(IPAddress.Any, 80);*/         // http:*:80                 
                    //options.Listen(IPAddress.Any, 5001, listenOptions =>
                    //{
                    //  listenOptions.UseHttps("certificate.pfx", "password");
                    //});
                });

here is the appsettings.json file:

{
  "https_port": 5001,
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "AllowInvalid": true,
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://*:80"
      }
    },
    "Https": {
      "Url": "https://*:5001",
      "Certificate": {
        "Path": "certificate.pfx",
        "Password": "password"
      }
    }
  }
}

Solution

  • This article ended up having the solution I needed:

    https://www.humankode.com/asp-net-core/develop-locally-with-https-self-signed-certificates-and-asp-net-core

    To be more precise its the part of the article titled "Configuring HTTPS in ASP.NET Core 2.0"

    Instead of using appsettings.json, I created a new json file called certificate.json.

    I then pull in the certificate name and password from the certificate.json into the program.cs code.