Enabling Windows Identity Foundation within a Web Service

WIF provides easy integration with WCF. This lets a WCF service use WIF features, such as the new claims model, support for additional security token types (SAML 2.0), and token handling. This section shows how to do this.

To Enable Windows Identity Foundation in a Self-Hosted WCF Service

  1. In Visual Studio, add a reference to the WIF assembly (Microsoft.IdentityModel.dll) to the WCF service project.

  2. Add code that calls the ConfigureServiceHost method and passes it a service host instance for which to enable WIF. You must do this before you call ServiceHost.Open() on that instance. This method makes the necessary changes to the ServiceHost instance settings to integrate WIF features with the WCF message processing pipeline. The following code sample shows how to do this:

  Copy Code
using (ServiceHost host = new ServiceHost(typeof(ClaimsAwareWebService), new Uri("http://localhost:6020/ClaimsAwareWebService")))
  {
	 // Configure WIF on the service host
	 FederatedServiceCredentials.ConfigureServiceHost(host);

	 host.Open();

	 Console.WriteLine(“Service is ready, press ENTER to close ...”);
	 Console.ReadLine();

	 host.Close()
   }

To Enable Windows Identity Foundation in a Web-Hosted WCF Service

  1. In Visual Studio, add a reference to the WIF assembly (Microsoft.IdentityModel.dll) to the WCF service project.

  2. Create a new class that inherits from ServiceHostFactory.

  3. Override the CreateServiceHost method. In the implementation, first call base.CreateServiceHost( string, Uri[] ) to create the ServiceHost instance. Then perform any programmatic configuration of the ServiceHost instance that your application requires. Then call ConfigureServiceHost to enable WIF features on that ServiceHost instance. Finally, return the configured instance as a return value of the CreateServiceHost method.

The following code sample shows a custom ServiceHostFactory that enables WIF features for the created ServiceHost:

  Copy Code
public class MyServiceHostFactory : ServiceHostFactory
	{
		public override ServiceHostBase CreateServiceHost( string constructorString, Uri[] baseAddresses )
		{
			ServiceHostBase host = base.CreateServiceHost( constructorString, baseAddresses );
			FederatedServiceCredentials.ConfigureServiceHost( host );
			return host;
	}
}

Because a custom service host factory is used to enable WIF features in the Web-hosted WCF service, the .svc file that is used to represent the WCF service endpoint must reference this service host factory by using the factory attribute, as shown here:

  Copy Code
<%@ServiceHost language=C# Factory="Service1.MyServiceHostFactory" Service="Service1.Service1"%>