Microsoft WCF Security

Microsoft WCF 4.0 - Over 85 easy recipes for managing communication between applications with Microsoft Windows Communication Foundation 4.0 in this book and eBook

        Read more about this Microsoft WCF book      

(For more resources on Microsoft, see here.)


Security is a big topic in distributed communication applications. When the client consumers call a service operation through an intranet or the Internet, it is necessary to consider how we will secure the communication between the two sides, or how we can make sure that we are talking to the correct service or the correct client consumers.

WCF provides a lot of built-in features for developers to address all these kinds of problems in service application development. The most commonly used WCF security features include authentication, authorization, and message protection (signing and encrypting).

In this article, we will use 5 recipes to demonstrate some useful security scenarios in WCF service development. These recipes will focus on various authentication use cases, including Windows authentication, username authentication, and so on.

Setting up ad hoc Windows authentication over plain HTTP

WCF supports various authentication types and Windows authentication is a common authentication method used in existing distributed communication components on the Windows platform. A very common use case is to enable Windows authentication at transport layer without an additional secure connection like SSL (just like what the traditional ASMX Web Service uses).

In this recipe, we will demonstrate how to apply Windows authentication for a WCF service endpoint using plain HTTP as the transport protocol, without additional security.

How to do it...

  1. Make the service endpoint use BasicHttpBinding.
    The first thing to do is choose BasicHttpBinding as the binding type of our WCF service endpoint. Also, in the binding configuration, we need to specify the security mode as TransportCredentialOnly and clientCredentialType as Windows. The following screenshot shows the app.config section of our sample service endpoint.

  2. Adjust the Windows authentication settings in IIS server.
    For a WCF service, if we use IIS as the hosting environment, we also need to apply proper configuration on the application virtual directory in which we will deploy the service endpoints. For our ad hoc Windows authentication service, it is necessary to turn on the Windows authentication and disable anonymous access on the IIS virtual directory so that the Windows authentication on the WCF endpoint can work correctly. All these configurations can be done through the IIS virtual directory settings in the management console. The following screenshot shows the configuration manager UI of IIS 7.

How it works...

After the service endpoint has been properly configured as ad hoc Windows authentication mode, the client consumer can use the generated proxy class or ChannelFactory to invoke the target service operations. Also, either the service proxy or ChannelFactory provides the ClientCredential property for the caller to supply their Windows credentials (see the following code snippet):

static void CallService()
TestProxy.Service1Client client = new TestProxy.Service1Client();

client.ClientCredentials.Windows.ClientCredential =

Console.WriteLine( client.GetData(11));

Getting an authenticated client identity in a service operation

WCF provides various built-in authentication methods either at the transport layer or at the message layer. The client consumer can use a WCF service proxy or ChannelFactory to supply certain client credentials to the service. The following MSDN reference lists all the built-in credential types supported by WCF:

After the service request passes authentication, a valid identity will be associated with each service-operation execution context and the service operation code can retrieve the identity information within the operation context.

This recipe will show you how to programmatically retrieve the client authenticated identity information in service operation code.

How to do it...

WCF runtime provides an OperationContext object associated with each request processing so that the developers can access some operation/request context-specific data from it. For example, we can access and manipulate SOAP headers or other underlying transport protocol properties through OperationContext. For operation authentication, the authenticated identity is also accessible through OperationContext, and the minor difference is that we need to get the identity by a ServiceSecurityContext member of the OperationContext object. The ServiceSecurityContext type contains several member properties, which represent security information transferred from the client side.




Returns an instance of the ServiceSecurityContext class that contains an empty collection of claims, identities, and other context data usually used to represent an anonymous party.


Gets the authorization information for an instance of this class. The AuthorizationContext contains a collection of ClaimSet that the application can interrogate, and retrieve the information of the party.


Gets the collection of policies associated with an instance of this class.


Gets the current ServiceSecurityContext.


Gets a value that indicates whether the current client has provided credentials to the service.


Gets the primary identity associated with the current setting.


Gets the Windows identity of the current setting.

The WindowsIdentity and PrimaryIdentity properties are the corresponding members which contain the authentication identity information of the client service caller. We can inspect the identity details such as identity name or authentication type from the two properties. The following screenshot shows the code for obtaining main authentication identity information from the PrimaryIdentity property.

Likewise, we can use the Windows Identity property to get the Windows security identity associated with the current operation call (as shown in the following screenshot):

        Read more about this Microsoft WCF book      

(For more resources on Microsoft, see here.)

Using username authentication with an ASP.NET membership provider

WCF supports username authentication, which requires the service caller to supply a username/password token for validation. By default, if we simply turn on username authentication at the message layer, the WCF service runtime will use the Windows SAM database to validate the username/password credentials. However, we can also use our custom database or account storage to perform the validation, and if you are familiar with ASP.NET web application development, you will find it quite convenient to directly use the ASP. NET membership database for WCF username authentication.

In this recipe, we will show you how to enable username authentication against the ASP.NET membership database for a WCF service. And we will use a web application for hosting our sample WCF service which uses the ASP.NET membership database for username token validation.

How to do it...

  1. Enable an ASP.NET membership provider and user accounts.
    The first thing to do is enable an ASP.NET membership provider in our web application. The following screenshot shows the complete membership provider configuration fragment, which includes the provider and connectionString section. The membership provider will reference the connectionString through the connectionStringName attribute . For our sample service, we use the default SQL Express database file as the account database. Also, our user-defined membership provider needs to be set as defaultProvider so that the ASP.NET and WCF application will use it automatically (see the defaultProvider attribute in the next screenshot).

    After enabling the proper membership provider, we need to add some user accounts for testing. In our sample service, we use the ASP.NET web application Global.asax component to initialize some test accounts; the initialize code will add a predefined account named user1 (see the Global class in the following screenshot).

  2. Configure our WCF service to use a membership provider for username authentication.
    Our sample service will use wsHttpBinding along with a username authentication type as shown in the following screenshot:

    Although we have registered our custom membership provider and added test user accounts, WCF username authentication will not automatically choose ASP.NET membership as the repository for validating the username account. To make the WCF service username authentication validation associated with our predefined membership provider, we need to manipulate the serviceBehavior of the WCF service. The following screenshot shows the serviceBehavior fragment that makes our WCF service use the membership provider for username authentication validation.

    As we can see, the userNameAuthentication element has two attributes defined. The userNamePasswordValidationMode controls what we use for username validation; here it is set to MembershipProvider. And the membershipProviderName further identifies which membership provider is selected as the one that will be called by the WCF username validation code.

How it works...

With the membership provider and WCF service correctly configured, any requests from the client (with a username token attached in the message) will be validated through the membership provider. For our sample service, the client caller should provide the correct account credentials, which are stored in the membership provider database at the service side (see the following code snippet):

private static void CallService()
TestProxy.Service1Client client = new TestProxy.Service1Client();

client.ClientCredentials.UserName.UserName = "user1";
client.ClientCredentials.UserName.Password = "user1@password";


Sending a clear text username token over unsecured HTTP transport

For a WCF service endpoint that uses the username authentication type, it requires, by default, the service endpoint to secure the service channel through either message-layer or transport-layer security. In other words, we need to either use the HTTPS transport protocol or message-layer signing and encryption to make the service endpoint able to transfer a username token. However, for some very special cases, we might need to send clear text username/password credentials (for username authentication) over an unsecured HTTP channel. Though this is not supported out of the box, there still exists some workarounds that can help us achieve this. Yaron Naveh has created ClearUsernameBinding , which successfully achieves this goal. Here we will demonstrate how to apply this ClearUsernameBinding in our own WCF HTTP service.

Getting ready

The full source code of ClearUsernameBinding and samples can be found at the following location:

How to do it...

Now, let's go through the detailed steps about how we can apply ClearUsernameBinding in our service.

  1. Register ClearUsernameBinding.
    To use the ClearUsernameBinding, we need to first add a reference to the ClearUsernameBinding.dll assembly in the projects that will host the WCF service and run the WCF client. WCF provides various extension points that allow developers to extend the existing bindings or binding elements. The next screenshot shows the configuration fragment that registers ClearUsernameBinding in the app.config file.

  2. Configure the service endpoint to use ClearUsernameBinding.
    The next step is to make our WCF service endpoint use ClearUsernameBinding. Since we have already defined the ClearUsernameBinding extension, what we need to do is to just change the binding attribute of the service endpoint to clearUsernameBinding.

  3. Use a custom UsernamePasswordValidator for testing.
    By default, WCF will validate a username token against the Windows account system. To override this in our sample service, we create a test UsernamePasswordValidator that will allow any account from the client to pass validation. The custom UsernamePasswordValidator can be enabled through the element in the setting, as shown in the following screenshot.

    Since this custom UsernamePasswordValidator is for testing purposes, we will not put any real validation code logic in it. The code snippet in the following screenshot shows the implementation code of our test username password validator, which simply returns so as to pass the validation.

How it works...

To consume the WCF service that uses ClearUsernameBinding, we can use a programmatically generated ChannelFactory instance , as shown in the following code snippet:

private static void CallService()
ClearUsernameBinding binding = new ClearUsernameBinding();

ChannelFactory<HttpServiceApp.IHelloWorld> factory =
new ChannelFactory<HttpServiceApp.IHelloWorld>(
factory.Credentials.UserName.UserName = "WCFUser";
factory.Credentials.UserName.Password = "Password";

HttpServiceApp.IHelloWorld helloproxy = factory.CreateChannel();


As the service endpoint is using a plain HTTP transport channel (without SSL) and no message security, we can use network trace tools like Fiddler to capture the SOAP message that contains the username token in clear text format (shown in the next screenshot).

Using transport and message security at the same time

WCF supports both transport- and message-layer security. By using transport-layer security, the SOAP message of our WCF service operation is completely unsecured, and the transport protocol (such as HTTPS, TCP) helps to secure the data transferred over them. By using message-layer security, the SOAP message itself is secured and the WCF runtime needs to perform the message-secure processing. Generally, we suggest that to developers that using either of the transport- or message-layer security is enough and this is also what the built-in system bindings allow us to do. However, it is still necessary to apply secure protection at both layers in some cases, especially when talking to some non-WCF service platforms. This recipe will use a simple HTTP-based WCF service to demonstrate how to apply secure protection at both transport and message layer.

How to do it...

Since built-in system bindings only support enabling security at one layer (either the transport or the message layer), what we can do to enable security at both layers is to leverage the custom binding. Here we will use a sample service over HTTP transport to demonstrate the scenario. The security settings we use at both layers are as follows:

  • Transport layer: HTTPS/SSL channel
  • Message layer: Username authentication secured by certificate

We use the app.config file to define the custom binding stack. The following screenshot shows the custom binding with all the necessary binding elements defined.

As we can see, the <httpsTransport> binding element represents the HTTPS-based transport channel and the <security> element represents the secure channel at the message layer.

When consuming this service, the client caller needs to take care of both the HTTPS channel at the transport layer and the X.509 certificate-based username authentication at the message layer.

How it works...

By turning on the WCF message-logging feature, we can get the underlying message at the message layer. The SOAP message at the service layer is secured via the username authentication token and X.509 certificate. The following screenshot shows the raw SOAP message captured at the WCF service layer.

At the transport layer, the message is further signed and encrypted by the SSL/TLS channel. The next screenshot shows the transport message information captured in Fiddler.


This article demonstrated how to utilize the built-in WCF security features such as Windows authentication, username authentication, message protection, and so on.

Further resources on this subject:

Books to Consider

comments powered by Disqus

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free