2023-08-12 18:35:57 +01:00
|
|
|
using System.Security.Cryptography.X509Certificates;
|
|
|
|
|
2023-08-13 17:33:54 +01:00
|
|
|
namespace OliverBooth.Extensions;
|
2023-08-12 18:35:57 +01:00
|
|
|
|
2023-08-12 20:13:47 +01:00
|
|
|
/// <summary>
|
|
|
|
/// Extension methods for <see cref="IWebHostBuilder" />.
|
|
|
|
/// </summary>
|
2023-08-12 18:35:57 +01:00
|
|
|
public static class WebHostBuilderExtensions
|
|
|
|
{
|
2023-08-12 20:13:47 +01:00
|
|
|
/// <summary>
|
|
|
|
/// Adds a certificate to the <see cref="IWebHostBuilder" /> by reading the paths from environment variables.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="builder">The <see cref="IWebHostBuilder" />.</param>
|
|
|
|
/// <param name="httpsPort">The HTTPS port.</param>
|
|
|
|
/// <param name="httpPort">The HTTP port.</param>
|
|
|
|
/// <returns>The <see cref="IWebHostBuilder" />.</returns>
|
|
|
|
public static IWebHostBuilder AddCertificateFromEnvironment(this IWebHostBuilder builder,
|
|
|
|
int httpsPort = 443,
|
|
|
|
int httpPort = 80)
|
2023-08-12 18:35:57 +01:00
|
|
|
{
|
|
|
|
return builder.UseKestrel(options =>
|
|
|
|
{
|
|
|
|
string certPath = Environment.GetEnvironmentVariable("SSL_CERT_PATH")!;
|
2023-08-13 17:33:54 +01:00
|
|
|
if (string.IsNullOrWhiteSpace(certPath))
|
|
|
|
{
|
|
|
|
Console.WriteLine("Certificate path not specified. Using HTTP");
|
|
|
|
options.ListenAnyIP(httpPort);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-08-12 18:35:57 +01:00
|
|
|
if (!File.Exists(certPath))
|
|
|
|
{
|
2023-08-13 17:33:54 +01:00
|
|
|
Console.Error.WriteLine("Certificate not found. Using HTTP");
|
2023-08-12 20:13:47 +01:00
|
|
|
options.ListenAnyIP(httpPort);
|
2023-08-12 18:35:57 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
string? keyPath = Environment.GetEnvironmentVariable("SSL_KEY_PATH");
|
2023-08-13 17:33:54 +01:00
|
|
|
if (string.IsNullOrWhiteSpace(keyPath))
|
2023-08-12 18:35:57 +01:00
|
|
|
{
|
2023-08-13 17:33:54 +01:00
|
|
|
Console.WriteLine("Certificate found, but no key provided. Using certificate only");
|
|
|
|
keyPath = null;
|
|
|
|
}
|
|
|
|
else if (!File.Exists(keyPath))
|
2023-08-12 18:35:57 +01:00
|
|
|
{
|
2023-08-13 17:33:54 +01:00
|
|
|
Console.Error.WriteLine("Certificate found, but the provided key was not. Using certificate only");
|
|
|
|
keyPath = null;
|
2023-08-12 18:35:57 +01:00
|
|
|
}
|
2023-08-13 17:33:54 +01:00
|
|
|
|
|
|
|
Console.WriteLine($"Using HTTPS with certificate found at {certPath}:{keyPath}");
|
|
|
|
var certificate = X509Certificate2.CreateFromPemFile(certPath, keyPath);
|
|
|
|
options.ListenAnyIP(httpsPort, configure => configure.UseHttps(certificate));
|
2023-08-12 18:35:57 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|