How to fake Transport Security in WCF

Published April 14, 2009 by Toran Billups

I have spent the last 18 months in and out of the WCF stack but until recently I had no reason to write a custom binding. This has been in part because WCF out of the box offers enough configuration options that I did not need to get my hands dirty. This was a big reason I took a step toward WCF and a step away from ASMX in 2007. Especially when it comes to SOAP and the usual WS* mess everyone in the web service world loves so much. With WCF you get all the SOAP 1.1 / 1.2 work done for you, among a ton of other messaging configurations. And if you are working in or around the enterprise like I do, you can also tap into the membership provider to leverage role based access with a few simple attributes.

In my first few 'demo-ware' applications to get hype around WCF I used a simple WsHttpBinding coupled with the membership provider via service behavior.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  <system.serviceModel>
		<services>
			<service name='SampleApplicationWCF.Library.ProductService' behaviorConfiguration='NorthwindBehavior'>
				<endpoint address='' name='wsHttpProductService' contract='SampleApplicationWCF.Library.IProductService' binding='wsHttpBinding' bindingConfiguration='wsHttp'/>
			</service>
		</services>
		<bindings>
			<wsHttpBinding>
				<binding name='wsHttp'>
					<security mode='TransportWithMessageCredential'>
						<transport/>
						<message clientCredentialType='UserName' negotiateServiceCredential='false' establishSecurityContext='true'/>
					</security>
				</binding>
			</wsHttpBinding>
		</bindings>
		<behaviors>
			<serviceBehaviors>
				<behavior name='NorthwindBehavior'>
					<serviceMetadata httpGetEnabled='true'/>
					<serviceAuthorization principalPermissionMode='UseAspNetRoles'/>
					<serviceCredentials>
						<userNameAuthentication userNamePasswordValidationMode='MembershipProvider'/>
					</serviceCredentials>
				</behavior>
			</serviceBehaviors>
		</behaviors>
	</system.serviceModel>
  

But with these samples being just that, they never got implemented in our production environment. But late last year another developer came to me with a project that had a requirement to interop with someone outside of our network. I took on a mentor role as I thought I knew it all ... and we got a working solution ready for a migration to staging. And to my surprise I found that WCF required SSL be installed on the IIS server(s) when you use the security mode TransportWithMessageCredential inside a WsHttpBinding. This makes sense as you want to ensure SSL is setup when you start throwing around usernames and passwords.

In my case it turns out I had not done my homework with regards to our infrastructure because the production enviornment had a proxy that sits in front of the load balanced IIS farm. And it was on this proxy that our SSL certs are installed (instead of on the IIS box themselves). Here is where I ran into my dilemma ...

We needed a solution that would allow the WSDL to be pulled from an individual IIS server via the farm, yet ensure usernames were not being thrown around in plain text. The solution came from a cry of desperation on stackoverflow after I had exhausted almost 2 weeks worth of R&D with almost no results.

The only answer I got on stackoverflow pointed me to this post

And from this post I was pointed to another

Armed with a new set of information it looked as if I could 'fake' the Transport so the WCF service would 'function' like the normal WsHttpBinding even if the IIS server itself did not have any sort of SSL cert installed.

I could have pointed to the posts above and called it quits, but what I found is that they did not seem to be 100% complete. This is where I come in.

The first class that you need to create will represent a custom binding element for our 'faked' transport binding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace App.BindingExtenions {
    public class HttpsViaProxyTransportBindingElement : HttpTransportBindingElement, ITransportTokenAssertionProvider {
        public override T GetProperty<T>(BindingContext context) {
            if (typeof(T) == typeof(ISecurityCapabilities))
                return (T)(ISecurityCapabilities)new AutoSecuredHttpSecurityCapabilities();

            return base.GetProperty<T>(context);
        }

        public override BindingElement Clone() {
            return new HttpsViaProxyTransportBindingElement();
        }

        public System.Xml.XmlElement GetTransportTokenAssertion() {
            return null;
        }
    }
}

Next you will need to create a custom implementation of the ISecurityCapabilities interface to satisfy the dependency found in the above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace App.BindingExtenions
{
    public class AutoSecuredHttpSecurityCapabilities : ISecurityCapabilities
    {
        public ProtectionLevel SupportedRequestProtectionLevel
        {
            get { return ProtectionLevel.EncryptAndSign; }
        }

        public ProtectionLevel SupportedResponseProtectionLevel
        {
            get { return ProtectionLevel.EncryptAndSign; }
        }

        public bool SupportsClientAuthentication
        {
            get { return false; }
        }

        public bool SupportsClientWindowsIdentity
        {
            get { return false; }
        }

        public bool SupportsServerAuthentication
        {
            get { return true; }
        }

    }
}

And finally you will need to create one last class to represent the actual transport element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace App.BindingExtenions {
    public class HttpsViaProxyTransportElement : HttpTransportElement {

        public override Type BindingElementType {
            get {
                return typeof(HttpsViaProxyTransportBindingElement);
            }
        }

        protected override TransportBindingElement CreateDefaultBindingElement() {
            return new HttpsViaProxyTransportBindingElement();
        }

    }
}

Now you have the binding Element Extension needed for this custom WCF Binding.

After you have the above compile friendly, add a reference to the assembly from your WCF Service project.

Below is a very simple example of how to use this custom binding in your config file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  <system.serviceModel>
    <services>
      <service name='SampleApplicationWCF.Library.Service.ProductService' behaviorConfiguration='NorthwindBehavior'>
        <endpoint address='' name='wsHttpProductService' contract='SampleApplicationWCF.Library.Service.Interfaces.IProductService' binding='customBinding' bindingConfiguration='UserNamePasswordSecured'/>
      </service>
    </services>
    <extensions>
      <bindingElementExtensions>
        <add name='httpsViaProxyTransport' type='App.BindingExtenions.HttpsViaProxyTransportElement, ClearTextBinding'/>
      </bindingElementExtensions>
    </extensions>
    <bindings>
      <customBinding>
        <binding name='UserNamePasswordSecured'>
          <textMessageEncoding />
          <security authenticationMode='UserNameOverTransport' />
          <httpsViaProxyTransport />
        </binding>
      </customBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name='NorthwindBehavior'>
          <serviceDebug includeExceptionDetailInFaults='true'/>
          <serviceMetadata httpGetEnabled='true'/>
          <serviceAuthorization principalPermissionMode='UseAspNetRoles'/>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode='MembershipProvider'/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  

And finally - the best part is that you do not need to add this custom assembly to your client app. Instead your client app can keep the config settings to reflect a normal WsHttpBinding. The only item you need to confirm is set in your client binding is the security section (shown in the below client config)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name='ServiceCustomBinding' receiveTimeout='12:59:59' >
          <reliableSession ordered='false' inactivityTimeout='12:58:59'/>
          <security mode='TransportWithMessageCredential'>
            <transport clientCredentialType='None'/>
            <message clientCredentialType='UserName' establishSecurityContext='false' />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address='https://proxyserver/app/productservice.svc'
          binding='wsHttpBinding' bindingConfiguration='ServiceCustomBinding'
          contract='ProductService.IProductService' name='wsHttpProductService' />
    </client>
  </system.serviceModel>
  

The final tweak needed is at the service level (in your WCF project) to avoid any Address Mismatch error you might get

1
2
3
4
5
6
7
8
9
10
11
12
13
namespace Service
    {
        [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
        public class ProductService : IProductService
        {
           public IEnumerable<Product> GetProductCollection()
           {
               return null;
           }

       }
   }
  

Now when my client app connects to the web service via the proxy (https) I actually connect to the IIS server w/out any SSL cert installed. (A-Ha! We have faked the transport with message creds!)

If you want to investigate further, download the source here

Update:If you download the sample above keep in mind that I only included the class library needed to produce the assembly for the custom binding, not a sample WCF service project or sample client project. The 2 configuration files included are valid examples of how one might use this custom binding to setup communication between a WCF SOAP web service and a client application.


Buy Me a Coffee

Twitter / Github / Email