WCF: Windows Authentication with basicHttpBinding

Most developers when developing Windows Communication Foundation (WCF) services, will take security for granted and deploy their web services unsecured. In this post, I'm going to discuss how we can easily configure a WCF web service to use Windows Authentication.

In the services config file, configure the security settings for the binding as follows:

<bindings>
  <basicHttpBinding>
    <binding name="basicHttp">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows"/>
      </security>
    </binding>
  </basicHttpBinding>

</bindings>

Take note that I'm using basicHttpBinding for my web services.

Make sure that the service is using the binding configuration.

<service name="SecureDemo.Services.MyService">
  <endpoint name="basicHttpMyService" 
            address="" 
            binding="basicHttpBinding" 
            bindingConfiguration="basicHttp"  
            contract="SecureDemo.Services.Contracts.IMyService"/>

</service>

WCF requires that both the consumer and service configurations to be the same. Therefore, at the client config file, include the same binding configuration and then configure the client to use it.

<client>
    <endpoint name="basicHttpMyService"
              address="http://localhost:8888/MyService"
              binding="basicHttpBinding" 
              bindingConfiguration="basicHttp"
              contract="SecureDemo.Services.Contracts.IMyService" 
    />

</client>

That's all for the configuration. Now when you call the service, simply supply the credentials like the following example:

var proxy = new MyServiceClient();

proxy.ClientCredentials.Windows.ClientCredential.UserName = "HelloKitty";
proxy.ClientCredentials.Windows.ClientCredential.Password = "meowmeow";
proxy.ClientCredentials.Windows.ClientCredential.Domain = "cutieland";

You can substitute the hard-coded credentials with values retrieved from your login screen if you want to authenticate by individual account and not from an application service account.

Hope this was helpful. :)

No comments:

Post a Comment