Tuesday, 26 February 2013

WCF Restful service with BASIC Authentication

Just wanted to show code for configuring BASIC authentication on REST service.

Hosting part
---------------
               WebHttpBinding binding = new WebHttpBinding();
                binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                binding.Security.Transport.Realm = "domain"; //Enter domain name

                host = new WebServiceHost(typeof(Service), address.Uri);
                host.AddServiceEndpoint(typeof(IService), binding, address.Uri);
                host.Open();

Client
--------
           WebHttpBinding binding = new WebHttpBinding();

            binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
           
            using (WebChannelFactory factory = new WebChannelFactory(binding, address.Uri))
            {
                factory.Credentials.UserName.UserName = "user";
                factory.Credentials.UserName.Password = "password";

                var channel = factory.CreateChannel();

                channel.CallSomething();
            }

No comments: