HTTPS for Local Service Fabric Local

Create a secure cluster locally:

Run as admin powershell the following command:
.\DevClusterSetup.ps1 -PathToClusterDataRoot "C:\SfDevCluster\Data" -PathToClusterLogRoot "C:\SfDevCluster\Log" -AsSecureCluster -CreateOneNodeCluster
 In folder: C:\Program Files\Microsoft SDKs\Service Fabric\ClusterSetup

Note
Make sure and select the correct certificate when trying to connect to Service Fabric Explorer.
If the browser gives you a 403 error, try a different browser.


In Visual Studio, make sure your code matches the certificate:
Create this function:
public static X509Certificate2 GetCertificateFromStore()
{
    string aspNetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    if (string.Equals(aspNetCoreEnvironment, "Development", StringComparison.OrdinalIgnoreCase))
    {
        const string CNName = "CN=ServiceFabricDevClusterCert";
        using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
        {
            store.Open(OpenFlags.ReadOnly);
            var currentCerts = store.Certificates.Find(X509FindType.FindByIssuerDistinguishedName, CNName, false);
            return currentCerts.Count == 0 ? null : currentCerts[0];
        }
    }
    else
    {
        using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
        {
            store.Open(OpenFlags.ReadOnly);
            var certCollection = store.Certificates;
            var currentCerts = certCollection.Find(X509FindType.FindBySubjectName, "*.mydomain.com", false);
            return currentCerts.Count == 0 ? null : currentCerts[0];
        }
    }

}

Use it here (in <service name>.cs):
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners() { return new ServiceInstanceListener[] { new ServiceInstanceListener(serviceContext => new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) => { ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}"); return new WebHostBuilder() .UseKestrel(opt => { int port = serviceContext.CodePackageActivationContext.GetEndpoint("ServiceEndpoint").Port; opt.Listen(IPAddress.IPv6Any, port, listenOptions => { listenOptions.UseHttps(GetCertificateFromStore()); listenOptions.NoDelay = true; }); }) .ConfigureServices( services => services .AddSingleton<StatelessServiceContext>(serviceContext)) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None) .UseUrls(url) .Build(); })) }; }

Comments