How can I programmatically create this custom binding?

D.Forrest picture D.Forrest · Mar 31, 2010 · Viewed 21.8k times · Source

We've got to access a web service that uses soap11... no problem I'll just set the binding as:

BasicHttpBinding wsBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);

Nope. No dice. So I asked the host of the service why we're having authentication issues and he said that our config needed to have this custom binding:

<bindings>
    <customBinding>
        <binding name="lbinding">
            <security  authenticationMode="UserNameOverTransport" 
                messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11" 
                securityHeaderLayout="Strict" 
                includeTimestamp="false"
                requireDerivedKeys="true" 
                keyEntropyMode="ServerEntropy">
            </security>
            <textMessageEncoding messageVersion="Soap11" />
            <httpsTransport authenticationScheme ="Negotiate" requireClientCertificate ="false" realm =""/>
        </binding>
    </customBinding>
</bindings>

Only problem is we're creating our binding programmatically not via the config. So if someone could point me in the right direction in regards to changing my BasicHttpBinding into a custombinding that conforms to the .config value provided I'll give them a big shiny gold star for the day.

Answer

D.Forrest picture D.Forrest · Mar 31, 2010

Solved it!

Here's the winning code for those who are in a similar predicament.

Uri epUri = new Uri(_serviceUri);
CustomBinding binding = new CustomBinding();
SecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;        
sbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
sbe.IncludeTimestamp = false;
sbe.SetKeyDerivation(true);
sbe.KeyEntropyMode = System.ServiceModel.Security.SecurityKeyEntropyMode.ServerEntropy;
binding.Elements.Add(sbe);
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, System.Text.Encoding.UTF8));
binding.Elements.Add(new HttpsTransportBindingElement());
EndpointAddress endPoint = new EndpointAddress(epUri);