Search code examples
asp.net-corekestrel-http-server

How to access secrets in ASP.NET Core Program.cs


I am building an ASP.NET Core version 1.1 application that I want Kestrel to run over HTTPS/SSL. Here is the Program.cs bootstrap code...

public class Program
{
    public static void Main(string[] args)
    {
        var contentRoot = Directory.GetCurrentDirectory();
        var certFilePath = Path.Combine(contentRoot, @"Certificates\Kestrel.pfx");

        // TODO Store password in Secrets
        var certificate = new X509Certificate2(certFilePath, "kr0GEE6lJ5Ok");

        var host = new WebHostBuilder()
            .UseKestrel(cfg => cfg.UseHttps(certificate))
            .UseContentRoot(contentRoot)
            .UseSetting("detailedErrors", "true")
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("https://localhost:5001/")
            .CaptureStartupErrors(true)
            .Build();

        host.Run();
    }
}

This works as you might expect, but I would like to remove the certificate's password string from the code.

I have used the new (to me anyway) Secrets Manager Tool in the rest of the application, but I cannot find a way to reference this at this stage in the application pipeline.

Is this possible? If not, what other options might I look at?

Thanks.


Solution

  • I am not sure whether you can use the Secrets API. But you can read the password either from Environment variables or appsettings.json file. Here is the sample code. I am using .NET Core 2.0 code, which is similar to .NET Core 1.1.

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddEnvironmentVariables()
                .AddJsonFile("appsettings.json");
    
            Configuration = builder.Build();
            BuildWebHost(args).Run();
        }
        public static IConfigurationRoot Configuration { get; set; }
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args).UseKestrel(options =>
            {
                var password = Configuration["certPassword"];
                options.Listen(System.Net.IPAddress.Loopback, 5001, listenOptions =>
                {
                    listenOptions.UseHttps("testCert.pfx", password);
                    listenOptions.UseConnectionLogging();
                });
            })
            .UseStartup<Startup>()
            .Build();
    }
    

    Hope it helps.