How To: Use netTcpBinding with Windows Authentication and Transport security in WCF from Windows Forms

- J.D. Meier, Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen

Applies To

  • Windows Communication Foundation 3.5
  • Windows Forms
  • Microsoft® Visual Studio 2008

Summary

This how to shows you how to use the netTcpBinding with Windows Authentication and Transport security. NetTcpBinding is used for communicating with WCF clients in an intranet and provides transport security and windows authentication by default. In this how to, the WCF service is hosted in a Windows service.

Contents

  • Objectives
  • Overview
  • Summary of Steps
  • Step 1 – Create a Windows Service
  • Step 2 – Create a Sample WCF Service
  • Step 3 – Modify the Windows Service to Host the WCF Service
  • Step 4 – Configure the WCF Service to use netTcpBinding with Transport Security
  • Step 5 – Configure the WCF Service to Publish Metadata
  • Step 6 – Install the Windows Service
  • Step 7 – Create a Test Client Application
  • Step 8 – Test the Client and WCF Service
  • Additional Resources

Objectives

  • Create a WCF service hosted in a Windows service
  • Expose the WCF service over the netTcpBinding to WCF enabled clients
  • Run the WCF service in the Network Service security context
  • Call the service from a Windows Forms test client

Overview

Windows Authentication is suited for scenarios in which your users have domain credentials. In the scenario described in this How To article, users are authenticated by Windows Authentication. The scenario described in this How To article uses the netTcpBinding binding to expose a WCF service to WCF-enabled clients. The netTcpBinding binding offers improved performance over an HTTP binding. Because IIS 6.0 cannot host a TCP binding, in this scenario WCF is hosted in a Windows service. The WCF service with netTcpBinding can be consumed by a WCF-enabled .NET application through the use of a service reference. The Visual Studio service reference generates a proxy class to abstract the underlying message-based communication. WCF transport security is used to support a secure communication channel in a point-to-point scenario. In general, you should always use transport security unless you need the additional flexibility that message security affords you. For example, you would use message security for scenarios in which there are intermediaries who need to inspect and re-route the message.
In this How To, you will create a Windows service to host your WCF service. You will then create sample WCF service in Visual Studio 2008 and configure the service to use netTcpBinding with transport security through the use of the WCF Configuration Editor. Next, you will configure a mexTcpBinding so that the service can expose its metadata to clients from which they can generate a WCF proxy and call your service. Finally, you will create a test client to verify that the service is working properly.
Solution Summary
  • Binding: By default, netTcpBinding offers improved performance over an HTTP binding and is the ideal choice for cross machine communication between WCF clients and a WCF service, in an intranet.
  • Security Mode: Transport security is the default security mode for netTcpBinding and should be preferred over Message security for better performance. If needed, message security can provide greater control over signing and encryption of the message.
  • Client Authentication: Since this binding is used inside an intranet, Windows is the default and recommended client authentication mechanism. The other options for this binding are None for anonymous authentication and Certificate.
  • Protection Level: It is recommended to stick to the default EncryptAndSign protection level for maximum transport security. This can be lowered to Sign for performance but None is typically not recommended.
  • Hosting Consideration: This how-to hosts WCF in a Windows service. In general, netTcpBinding services can be hosted in a windows service, IIS 7.0 (not IIS 6.0 or lower), WAS or can be self-hosted. The choice should be based on the deployment requirements of the service.

Summary of Steps

  • Step 1 – Create a Windows Service
  • Step 2 – Create a Sample WCF Service
  • Step 3 – Modify the Windows Service to Host the WCF Service
  • Step 4 – Configure the WCF Service to use netTcpBinding with Transport Security
  • Step 5 – Configure the WCF Service to Publish Metadata
  • Step 6 – Install the Windows Service
  • Step 7 – Create a Test Client Application
  • Step 8 – Test the Client and WCF Service

Step 1 – Create a Windows Service

In this step, you will create a Windows service to host your WCF service.
  1. In Visual Studio, from the menu select File -> New -> Project.
  2. In the New Project Dialog, in the Project Types section select Windows under Visual C#.
  3. In the Templates section, select Windows Service and specify the project location and name it as “WCFServicecHost”.
  4. Click Ok on the Add a Project dialog box; this will add a sample Windows service to the solution.
  5. Right click the Service1.cs and select View Designer.
  6. Right click the designer view and select Add Installer, this will add ProjectInstaller.cs file with two objects, serviceProcessInstaller1 and serviceInstaller1.
  7. In the designer view of ProjectInstaller.cs, right click on serviceProcessInstaller1 and click Properties.
  8. In the properties section set the Account attribute to NetworkService. This will run your Windows service under the Network Service account.

Step 2 – Create a Sample WCF Service

In this step you will add a WCF Service to the windows service which will host it.
  1. Right click on the Widows Service project and select Add -> New Item.
  2. In the Add New Item dialog box select WCF Service.
  3. Set the Name as MyService.cs and click the Add button.
  4. Note that the configuration file, App.config file gets automatically added.
  5. Modify the DoWork() method in the IMyService.cs and MyService.cs to accept a string parameter and return a string data type as below.
public string DoWork(string value)
{
      return "Welcome " + value;
}

Step 3 – Modify the Windows Service to Host the WCF Service

In this step, you override the OnStart() and OnStop() methods to start and stop the WCF Service inside the Windows Service process.
  1. Right click the Service1.cs in the solution explorer, and select View Code. In the Service1.cs file add a using statement as follows

using System.ServiceModel;
  1. Declare an internal static member of ServiceHost type, as follows

internal static ServiceHost myServiceHost = null;
  1. Override the OnStart method of a windows service, to open the service host as follows.
protected override void OnStart(string[] args)
{
   if (myServiceHost != null)
   {
       myServiceHost.Close();
   }

   myServiceHost = new ServiceHost(typeof(MyService));
   myServiceHost.Open();
}
  1. Override the OnStop method of a windows service, to close the service host as follows.
protected override void OnStop()
{
   if (myServiceHost != null)
   {
      myServiceHost.Close();
      myServiceHost = null;
   }
}
  1. Build the solution and verify that your project produces “WCFServicecHost.exe” in your project \bin directory.

Step 4 – Configure the WCF Service to use netTcpBinding with Transport Security

In this step, you configure your WCF Service, “MyService” to use netTcpBinding.
  1. Right click on the App.config file and select Edit WCF Configuration.
  2. In the configuration editor, expand the Services node and then expand the WCFHostService.MyService.
  3. Select the Host node, select the default BaseAddress from the Base addresses section and click the Delete button.
  4. Click the New button and in the Base Address Editor dialog box, set the Base address: to "net.tcp://localhost:8523/WCFTestService". The port number, “8523”, is arbitrary and just for this example. “WCFTestService” is also arbitrary and is used in this example to exposes the endpoint.
  5. Expand the Endpoints node and select the first end point created Empty Name and set the set the Name attribute to “NetTcpBindingEndpoint”
  6. Set the Binding attribute to netTcpBinding, overwriting the default wsHttpBinding, which you can choose from drop down.
  7. On the configuration editor dialog, got to File menu and select Save.
  8. In Visual Studio, verify your configuration in your App.config. The configuration should look as follows.
<services>
    <service behaviorConfiguration="WCFHostService.MyServiceBehavior"
        name="WCFHostService.MyService">
        <endpoint address="" *binding="netTcpBinding"*
               bindingConfiguration=""
               *name="NetTcpBindingEndpoint"*
               contract="WCFHostService.IMyService">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding"
                  contract="IMetadataExchange" />
        <host>
            <baseAddresses>
                <add *baseAddress="net.tcp://localhost:8523/WCFTestService"* />
            </baseAddresses>
        </host>
    </service>
</services>

Note - Because netTcpBinding supports Windows authentication with transport security by default, you don't have to change any other configuration in the binding.

Step 5 – Configure the WCF Service to Publish Metadata

In this step, you configure your WCF Service to publish Metadata. Publishing the Metadata will allow your client to add a reference to your WCF Service.
  1. In the configuration editor, expand the Services node, and then expand the WCFHostService.MyService node.
  2. Expand the Endpoints node and select the second end point created Empty Name and set the set the Name attribute to “MexTcpBindingEndpoint”
  3. Set the Binding attribute to mexTcpBinding, overwriting the default mexHttpBinding, which you can choose from drop down.
  4. On the configuration editor dialog, got to File menu and select Save.
  5. In Visual Studio, verify your configuration in App.config. The configuration should look as follows.
...
<services>
    <service behaviorConfiguration="WCFHostService.MyServiceBehavior"
        name="WCFHostService.MyService">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
            name="NetTcpBindingEndpoint" contract="WCFHostService.IMyService">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
        <endpoint address="mex" *binding="mexTcpBinding"* bindingConfiguration=""
            *name="MexTcpBidingEndpoint"* contract="IMetadataExchange" />
        <host>
            <baseAddresses>
                <add baseAddress="net.tcp://localhost:8523/WCFTestService" />
            </baseAddresses>
        </host>
    </service>
</services>
...
  1. In the configuration editor, expand the Advanced node, and then expand the Service Behaviors node.
  2. Expand the WCFHostService.MyServiceBehavior node and select the serviceMetadata node.
  3. Set the HttpGetEnabled attribute to False.
  4. On the configuration editor dialog, got to File menu and select Save.
  5. In Visual Studio, verify your configuration in App.config. The configuration should look as follows.
<behaviors>
    <serviceBehaviors>
        <behavior name="WCFHostService.MyServiceBehavior">
            <serviceMetadata *httpGetEnabled="false"* />
            <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
    </serviceBehaviors>
</behaviors>

Step 6 – Install the Windows Service

In this step, you install the Windows service and run it form the Services console.
  1. Re-build the solution and open a Visual Studio Command Prompt.
  2. Navigate to the bin directory of the project where the WCFServiceHost.exe copied.
  3. Execute the command > Installutil WCFServiceHost.exe to install the service.
  4. If the service is installed successfully then open the service console by typing services.msc in the Windows Run prompt.
  5. Search for the name of the service, Service1 and start it.

Note – If you have modified the service that is already installed then you can uninstall it by using following command:

> Installutil /u WCFServiceHost.exe

Step 7 – Create a Test Client Application

In this step, create a Windows Form application named “Test Client” to test the WCF Service.
  1. Right-click your Solution, click Add and then click New Project…
  2. In the Add New Project dialog box, select Windows Application from the Templates section.
  3. In the Name field, type Test Client and click Ok button. It will create a windows forms application.
  4. Right-click your client project and select Add Service Reference.
  5. In the Add Service Reference dialog box set the Service URI: to “net.tcp://localhost:8523/WCFTestService and click Go button.
  6. Service reference name: to “WCFTestService” and click Ok.

Step 8 – Test the Client and WCF Service

In this step you will use the test client to ensure the WCF service is running properly.
  1. In your Client project, drag a Button control to your Form.
  2. Double-click Button control to show the code behind.
In the code behind of the button click, create an instance of the proxy, and call DoWork of your WCF Service. When you call the service, your current user security context will automatically be passed to your WCF Service. The code should look as follows:
private void button1_Click(object sender, EventArgs e)
{
      WCFTestService.MyServiceClient myService = new
                             WCFTestService.MyServiceClient();
      MessageBox.Show(myService.DoWork("Hello World!"));
      myService.Close();
}
  1. Right click on the client project and select Set as Startup Project.
  2. Run the client application using F5 or Ctrl+F5, when you click the Button on the form it should display a message “Welcome Hello World!”

Additional Resources

Contributors and Reviewers

  • External Contributors and Reviewers:
  • Microsoft Consulting Services and PSS Contributors and Reviewers:
  • Test team: Rohit Sharma, Chaitanya Bijwe, Parameswaran Vaideeswaran.
  • Edit team: Dennis Rea.
  • SEO team: Rob Boucher.

Last edited Apr 30, 2008 at 10:24 PM by prashantbansode, version 6

Comments

No comments yet.