Programming WCF Security

Programming WCF Security


This topic describes the fundamental programming tasks used to create a secure Windows Communication Foundation (WCF) application. This topic covers only authentication, confidentiality, and integrity, collectively known as transfer security. This topic does not cover authorization (the control of access to resources or services); for information on authorization, see Authorization in WCF.


For a valuable introduction to security concepts, especially in regard to WCF, see the set of patterns and practices tutorials on MSDN at Scenarios, Patterns, and Implementation Guidance for Web Services Enhancements (WSE) 3.0.

Programming WCF security is based on three steps setting the following: the security mode, a client credential type, and the credential values. You can perform these steps either through code or configuration.

The following explains the general steps for programming with the security mode in WCF:

  1. Select one of the predefined bindings appropriate to your application requirements. For a list of the binding choices, see System-Provided Bindings. By default, nearly every binding has security enabled. The one exception is the BasicHttpBinding class (using configuration, the <basicHttpBinding>).

    The binding you select determines the transport. For example, WSHttpBinding uses HTTP as the transport; NetTcpBinding uses TCP.

  2. Select one of the security modes for the binding. Note that the binding you select determines the available mode choices. For example, the WSDualHttpBinding does not allow transport security (it is not an option). Similarly, neither the MsmqIntegrationBinding nor the NetNamedPipeBinding allows message security.

    You have three choices:

    1. Transport

      Transport security depends on the mechanism that the binding you have selected uses. For example, if you are using WSHttpBinding then the security mechanism is Secure Sockets Layer (SSL) (also the mechanism for the HTTPS protocol). Generally speaking, the main advantage of transport security is that it delivers good throughput no matter which transport you are using. However, it does have two limitations: The first is that the transport mechanism dictates the credential type used to authenticate a user. This is a drawback only if a service needs to interoperate with other services that demand different types of credentials. The second is that, because the security is not applied at the message level, security is implemented in a hop-by-hop manner rather than end-to-end. This latter limitation is an issue only if the message path between client and service includes intermediaries. For more information about which transport to use, see Choosing a Transport. For more information about using transport security, see Transport Security Overview.

    2. Message

      Message security means that every message includes the necessary headers and data to keep the message secure. Because the composition of the headers varies, you can include any number of credentials. This becomes a factor if you are interoperating with other services that demand a specific credential type that a transport mechanism can't supply, or if the message must be used with more than one service, where each service demands a different credential type.

      For more information, see Message Security in WCF.

    3. TransportWithMessageCredential

      This choice uses the transport layer to secure the message transfer, while every message includes the rich credentials other services need. This combines the performance advantage of transport security with the rich credentials advantage of message security. This is available with the following bindings: BasicHttpBinding, WSFederationHttpBinding, NetPeerTcpBinding, and WSHttpBinding

  3. If you decide to use transport security for HTTP (in other words, HTTPS), you must also configure the host with an SSL certificate and enable SSL on a port. For more information, see HTTP Transport Security.

  4. If you are using the WSHttpBinding and do not need to establish a secure session, set the EstablishSecurityContext property to false.

    A secure session occurs when a client and service create a channel using a symmetric key (both client and server use the same key for the length of a conversation, until the dialog is closed).

Select a client credential type as appropriate. For more information, see Selecting a Credential Type. The following client credential types are available:

  • Windows

  • Certificate

  • Digest

  • Basic

  • UserName

  • NTLM

  • IssuedToken

Depending on how you set the mode, you must set the credential type. For example, if you have selected the wsHttpBinding, and have set the mode to "Message," then you can also set the clientCredentialType attribute of the Message element to one of the following values: None, Windows, UserName, Certificate, and IssuedToken, as shown in the following configuration example.

    <binding name="myBinding">
      <security mode="Message"/>
      <message clientCredentialType="Windows"/>

Or in code:

private void MyEnumerator() {
    // Creates a new collection and assigns it the attributes for button1.
    AttributeCollection attributes;
    attributes = TypeDescriptor.GetAttributes(button1);

    // Creates an enumerator for the collection.
    System.Collections.IEnumerator ie = attributes.GetEnumerator();

    // Prints the type of each attribute in the collection.
    Object myAttribute;
    while(ie.MoveNext()==true) {
       myAttribute = ie.Current;
       textBox1.Text += myAttribute.ToString();
       textBox1.Text += '\n';

Once you select a client credential type, you must set the actual credentials for the service and client to use. On the service, credentials are set using the ServiceCredentials class and returned by the Credentials property of the ServiceHostBase class. The binding in use implies the service credential type, the security mode chosen, and the type of the client credential. The following code sets a certificate for a service credential.

// Create the binding for an endpoint.
NetTcpBinding b = new NetTcpBinding();
b.Security.Mode = SecurityMode.Message;

// Create the ServiceHost for a calculator.
Uri baseUri = new Uri("net.tcp://MachineName/tcpBase");
Uri[] baseAddresses = new Uri[] { baseUri };
ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddresses);

// Add an endpoint using the binding and a new address.
Type c = typeof(ICalculator);
sh.AddServiceEndpoint(c, b, "MyEndpoint");

// Set a certificate as the credential for the service.
catch (CommunicationException ce)
    Console.WriteLine("A commmunication error occurred: {0}", ce.Message);
catch (System.Exception exc)
    Console.WriteLine("An unforseen error occurred: {0}", exc.Message);

On the client, set client credential values using the ClientCredentials class and returned by the ClientCredentials property of the ClientBase<TChannel> class. The following code sets a certificate as a credential on a client using the TCP protocol.

private void ContainsAttribute() {
    // Creates a new collection and assigns it the attributes for button1.
    AttributeCollection attributes;
    attributes = TypeDescriptor.GetAttributes(button1);

    // Sets an Attribute to the specific attribute.
    BrowsableAttribute myAttribute = BrowsableAttribute.Yes;

    if (attributes.Contains(myAttribute))
       textBox1.Text = "button1 has a browsable attribute.";
       textBox1.Text = "button1 does not have a browsable attribute.";
© 2015 Microsoft