Home > Blockchain >  Configure ListenOptions.UseHttps with .pem file rather than .pfx in ASP.NET 6.0 app
Configure ListenOptions.UseHttps with .pem file rather than .pfx in ASP.NET 6.0 app

Time:03-22

I have an ASP.NET web app on ubuntu 20.04, and I am using SSL certificate in .pfx format, which works fine. However, I want to learn how to do the same with the .pem file.

I know it can be done in appsettings.json like this and through the HttpsFromPem key:

{
  "Kestrel": {
    "Endpoints": {
      "HttpsInlineCertAndKeyFile": {
        "Url": "https://localhost:5001",
        "Certificate": {
          "Path": "<path to .pem/.crt file>",
          "KeyPath": "<path to .key file>",
          "Password": "$CREDENTIAL_PLACEHOLDER$"
        }
      }
    }
  }
}

And I know how to use the .pfx format like so:

var httpsCert = Environment.GetEnvironmentVariable("HTTPS_CERT");
var httpsCertKey = Environment.GetEnvironmentVariable("HTTPS_CERT_KEY");

if (httpsCert != null && httpsCertKey != null)
{
    options.Listen(IPAddress.Loopback, 5001,
               listenOptions => listenOptions.UseHttps(httpsCert, httpsCertKey));
}

Source - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0

My question is: how to configure Kestrel to read cert from the .pem file in code?

CodePudding user response:

You can just load it in using

var pemPath = //read in from configuration
var privateKeyPath = //read in from configuration
var certificate = X509Certificate2.CreateFromPemFromFile(pemPath, privateKeyPath);

Then you can configure Kestrel with something like this when you're configuring Kestrel.

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.ConfigureKestrel(options =>
        {
            options.ConfigureHttpsDefaults(adapterOptions =>
            {
                adapterOptions.ServerCertificate = certificate
            });
        });
    }
  • Related