Is it possible to specify 2 different SSL certificates for a single instance of Kestrel server?

705 views Asked by At

I know there is a method "UseHttps" in the class "KestrelServerOptions" that accepts a single certificate, but is it possible to specify more than 1 SSL cert in order to be able to work with multiple domains and multiple certificates within a single instance of Kestrel?

1

There are 1 answers

0
Matan Shabtay On

It's possible by setting the ServerCertificateSelector property when calling UseHttps(). The selector is a callback that you implement by yourself and it is provided with a string parameter which indicates what is the DNS host used by the client to communicate with your server. You can treat this parameter and return the relevant certificate.

Taken from Microsoft docs:

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenAnyIP(5005, listenOptions =>
    {
        listenOptions.UseHttps(httpsOptions =>
        {
            var localhostCert = CertificateLoader.LoadFromStoreCert(
                "localhost", "My", StoreLocation.CurrentUser,
                allowInvalid: true);
            var exampleCert = CertificateLoader.LoadFromStoreCert(
                "example.com", "My", StoreLocation.CurrentUser,
                allowInvalid: true);
            var subExampleCert = CertificateLoader.LoadFromStoreCert(
                "sub.example.com", "My", StoreLocation.CurrentUser,
                allowInvalid: true);
            var certs = new Dictionary<string, X509Certificate2>(
                StringComparer.OrdinalIgnoreCase)
            {
                ["localhost"] = localhostCert,
                ["example.com"] = exampleCert,
                ["sub.example.com"] = subExampleCert
            };

            httpsOptions.ServerCertificateSelector = (connectionContext, name) =>
            {
                if (name is not null && certs.TryGetValue(name, out var cert))
                {
                    return cert;
                }

                return exampleCert;
            };
        });
    });
});