Sometimes, in a production environment, we need this kind of hosting due to some security reasons. To host a service through a program, we have to follow certain rules which make the process very easy.
I am not going to explain over here how to create certificates and import certificates. If you want to learn it, then refer to my earlier
article.
Now, we are directly jumping to the problem statement.
I am going to use these two certificates.
- Service Certificate
- Client Certificate
Note
Don't keep any service bindings in app.config.
Service Side Code
- ServiceHost svcHost = new ServiceHost(typeof(SampleWCFServiceLibrary.Service1));
-
- NetTcpBinding binding = new NetTcpBinding();
- binding.Security.Mode = SecurityMode.Message;
-
- binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
- svcHost.AddServiceEndpoint(typeof(SampleWCFServiceLibrary.IService1), binding, "net.tcp://127.0.0.1:8798/Service1");
-
- svcHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ServiceCert");
-
- svcHost.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ClientCert");
- svcHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
- svcHost.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine;
- svcHost.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
- svcHost.Credentials.ClientCertificate.Authentication.MapClientCertificateToWindowsAccount = false;
-
- svcHost.Open();
- Console.WriteLine("Service Hosted Sucessfully");
Client Code
- NetTcpBinding binding = new NetTcpBinding();
- binding.Security.Mode = SecurityMode.Message;
- binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
- EndpointAddress _endpoint = new EndpointAddress(new Uri("net.tcp://127.0.0.1:8798/Service1"), EndpointIdentity.CreateDnsIdentity("ServiceCert"));
-
-
- ServiceReference1.Service1Client svcClient = new ServiceReference1.Service1Client(binding, _endpoint);
-
- svcClient.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ClientCert");
-
-
- svcClient.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "ServiceCert");
- svcClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
-
- svcClient.Open();
-
- Console.WriteLine("Service is opened for me");
-
- string fromService = svcClient.GetData(143);
- Console.WriteLine(fromService);