views:

635

answers:

2

I'd like to convert my current HTTP/HTTPS WCF binding settings to use binary message encoding and I need to do it in code - not in XML configuration. AFAIK it's necessary to create CustomBinding object and set proper BindingElements, but I'm not able to figure out what elements should I use in my scenario.

Main points in my WCF configuration are:

  • use HTTP or HTTPS transport depending on configuration (in app.config)
  • use username message security
  • todo: add binary encoding instead of default text

My current code for setting the binding up (working, but without the binary encoding):

var isHttps = Settings.Default.wcfServiceBaseAddress.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase);
var binding = new WSHttpBinding(isHttps ? SecurityMode.TransportWithMessageCredential : SecurityMode.Message);
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

I was trying this code, but it doesn't work - I don't know how to set message security element for username message security:

var custBinding = new CustomBinding();
custBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
//Transport Security (Not Required)
if (isHttps)
{
    custBinding.Elements.Add(SecurityBindingElement.CreateUserNameForSslBindingElement());
}
//Transport (Required)
custBinding.Elements.Add(isHttps ?
    new HttpsTransportBindingElement() :
    new HttpTransportBindingElement());

Anybody knows how to set this up? I tried to search for similar problem/solution, but didn't succeeded...

A: 

Try SecurityBindingElement.CreateUserNameOverTransportBindingElement() instead:

var custBinding = new CustomBinding();
custBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
//Transport Security (Not Required)
if (isHttps)
{
  custBinding.Elements.Add(SecurityBindingElement.CreateUserNameOverTransportBindingElement());
}
//Transport (Required)
custBinding.Elements.Add(isHttps ?
   new HttpsTransportBindingElement() :
   new HttpTransportBindingElement());
Samuel Jack
I already tried this, but it doesn't work. Also when isHttps==false there's no message security setup - this is the main problem. I don't know how to setup WSHttpBinding-compatible message security using CustomBinding.
Buthrakaur
For security reasons, WCF only permits username/password combinations to be sent when the connection is encrypted - ie when you're using Https transport. This means that if you don't use Https, you can't secure your messages in this way. You might need to reassess your requirements.
Samuel Jack
A: 

The SecurityBindingElement has a AllowInsecureTransport property. If you set this to true you can use the HttpTransportBindingElement with message user name and password security.

Aaron Fischer