using System.Security.Cryptography.X509Certificates;
namespace OliverBooth.Extensions;
///
/// Extension methods for .
///
public static class WebHostBuilderExtensions
{
///
/// Adds a certificate to the by reading the paths from environment variables.
///
/// The .
/// The HTTPS port.
/// The HTTP port.
/// The .
public static IWebHostBuilder AddCertificateFromEnvironment(this IWebHostBuilder builder,
int httpsPort = 443,
int httpPort = 80)
{
return builder.UseKestrel(options =>
{
string certPath = Environment.GetEnvironmentVariable("SSL_CERT_PATH")!;
if (string.IsNullOrWhiteSpace(certPath))
{
Console.WriteLine("Certificate path not specified. Using HTTP");
options.ListenAnyIP(httpPort);
return;
}
if (!File.Exists(certPath))
{
Console.Error.WriteLine("Certificate not found. Using HTTP");
options.ListenAnyIP(httpPort);
return;
}
string? keyPath = Environment.GetEnvironmentVariable("SSL_KEY_PATH");
if (string.IsNullOrWhiteSpace(keyPath))
{
Console.WriteLine("Certificate found, but no key provided. Using certificate only");
keyPath = null;
}
else if (!File.Exists(keyPath))
{
Console.Error.WriteLine("Certificate found, but the provided key was not. Using certificate only");
keyPath = null;
}
Console.WriteLine($"Using HTTPS with certificate found at {certPath}:{keyPath}");
var certificate = X509Certificate2.CreateFromPemFile(certPath, keyPath);
options.ListenAnyIP(httpsPort, configure => configure.UseHttps(certificate));
});
}
}