Tuesday, December 25, 2007

WCF with Transport security and self-signed certificate

Say you want to create a secure WCF channel and not having the client verifying the server's certificate (maybe because you are testing or the server's certificate is self-signed and you don't want to install that certificate in the client's trusted certificate's store).

1) Configure the server this way:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="MyContract">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="NtlmSecurity"
contract="IMyContract" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="NtlmSecurity">
<security mode="Transport">
<transport clientCredentialType ="Ntlm" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>


2) Force not verifying the server's certificate. WARNING: this is intended only for test purposes. In production code, you don't want to avoid checking server's certificate at all.

private IMyContract GetChannel(Uri address)
{
// Create an endpoint address
EndpointAddress endpoint = new EndpointAddress(address);

// Create a binding
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
return (true);
});

// Create a channel to the service application endpoint
ChannelFactory<imycontract> factory = new ChannelFactory<IMyContract >(binding, endpoint);
return factory.CreateChannel();
}

No comments: