using System.Net; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.ServiceModel.Security; namespace PristupnaTockaSoapClient; public class SoapClientBuilder { public ServiceReference.BackendInterfaceClient BuildClient(String uri, String username, String password) { bool isHttps = new Uri(uri).Scheme.Equals("https"); ServiceReference.BackendInterfaceClient client = new ServiceReference.BackendInterfaceClient(GetBasicHttpBinding(isHttps), new EndpointAddress(uri)); client.ClientCredentials.UserName.UserName = username; client.ClientCredentials.UserName.Password = password; SetSSLAuth(client); SetAuthorizationHTTPHeader(client); return client; } private Binding GetBasicHttpBinding(bool isHttps) { BasicHttpBinding binding = new BasicHttpBinding(); binding.Security.Mode = isHttps ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private void SetAuthorizationHTTPHeader(ServiceReference.BackendInterfaceClient client) { // NOTE: Consider implementing custom IEndpointBehavior with custom IClientMessageInspector instead OperationContextScope context = new OperationContextScope(client.InnerChannel); HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); String usernamePassword = client.ClientCredentials.UserName.UserName + ":" + client.ClientCredentials.UserName.Password; httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(usernamePassword)); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; } private void SetSSLAuth(ServiceReference.BackendInterfaceClient client) { client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { TrustedStoreLocation = StoreLocation.CurrentUser }; } }