Choosing the Right Web Service Binding

WCF Bindings and Web Services Standards

15 Min Read
ITPro Today logo in a gray background | ITPro Today

Related: "WCF Proxies: To Cache or Not to Cache?" and "Going Mobile with WCF."

When I introduced this column last month I also providedan introduction to WCF as the new Web services technology to succeed ASP.NET Webservices (ASMX) and Web Services Enhancements (WSE) now that .NET 3.0 has beenreleased. In this column I ll help you make sense of the various HTTP bindingsthat WCF provides to support interoperable Web services. (For a backgrounder onhow to create your first WCF Web service see ASP.NET and WCF: Meet Your NewWeb Service in the February 2007 issue of asp.netPRO.)

 

Adoption of Web Services Standards

The term Web service has been around since SOAP protocolwas introduced in the late 1990s. With SOAP, a standard messaging format wasborn for exchanging messages between applications exposed to the Internet. Anaccompanying standard, Web Service Description Language (WSDL), made itpossible to describe a list of operations exposed by a particular Web service,and associate an XML schema for operation messages. SOAP and WSDL were thefirst widely adopted standards geared toward interoperability between operatingand technology platforms. Very soon after their introduction a slew of extendedstandards began to surface all with the goal of enhancing distributed andinteroperable communications.

Early implementations of Web services were primarilyconcerned with interoperability on a basic level. One of the biggest concernswas getting technology platforms to properly agree on how to interpret messageschema described by WSDL. Although some complex schema may still unveilincompatibilities, the great majority of Web service stacks interoperate wellon this level. In the past several years additional Web services standards havebeen ratified by the W3C (http://www.w3c.org)and by OASIS (http://www.oasis-open.org)to support message addressing and routing semantics, security, and for theoptimized transfer of binary data. Interoperability on many of these standardshas begun to stabilize across platforms, as we saw happen with SOAP and WSDL.Beyond these standards, even more standards for advanced security scenarios (reliablemessaging and transactions, to name a few) have gained wide industry supportand are on the verge of ratification. Despite pending ratification, popular Webservices technology platforms have already begun to support these standards forthe business value they offer.

Not only have these standards made interoperablecommunication possible, they have also enabled more reliable and securedistributed communication scenarios over any protocol. Message-basedcommunications can be based on these standards, regardless if they are exposedas interoperable Web services over HTTP or as non-interoperable, proprietaryservices over named pipes (IPC), TCP, MSMQ, or other transport protocols. Thismakes it possible to achieve end-to-end reliability and security over anyprotocol.

WCF was built from the ground-up with this in mind. Itsupports both ratified and emerging standards, while providing developers withthe flexibility to choose which to apply, and over what transport protocol.With WCF, you expose service endpoints by creating a contract, exposing thecontract at a particular address, and selecting a set of protocols supported bythe endpoint using a binding configuration. Not all WCF services are Webservices but they can be configured this way. In this article I ll discussoptions for exposing interoperable Web service endpoints with WCF.

 

Web Services Bindings

In the traditional sense of interoperable Web servicesexposed over HTTP, WCF provides three standard bindings: BasicHttpBinding,WSHttpBinding, and WSFederationHttpBinding. Collectively, these bindingssupport a wide range of ratified and emerging Web services standards, includingthe following: SOAP 1.1 and 1.2; WSDL; WS-Addressing; MTOM; WS-Security;WS-Trust; WS-SecureConversation; SAML 1.0 and 1.1; WS-ReliableMessaging;WS-AtomicTransaction; and WS-Policy, WS-SecurityPolicy, andWS-MetadataExchange. Your choice of WCF binding is a function of the desiredprotocols for your Web service endpoints.

Another HTTP binding, WSDualHttpBinding, supports duplexcommunication between client and service. With this binding, two Web service endpointsusing WSHttpBinding are exposed one at the service and another at the clientto facilitate callbacks or non-durable out-of-band calls from a service. Intheory, the messaging for each endpoint is interoperable, but the interactionto initiate duplex communication over HTTP is not part of a standard. Thus,WSDualHttpBinding is not considered an interoperable Web services binding.

In the following sections I ll cover BasicHttpBinding andWSHttpBinding, their support for ratified and emerging standards, and sometypical implementation scenarios and configurations.

 

BasicHttpBinding

BasicHttpBinding is primarily useful for exposing WCFservice endpoints that are compatible with earlier Web service stackssupporting Basic Profile 1.1, Basic Security Profile 1.0, and MTOM; forexample, ASMX and Web Services Enhancements (WSE). Basic Profile is aspecification produced by WS-I (http://www.ws-i.org)that provides guidance on how a basic set of Web service specifications such asSOAP 1.1, WSDL 1.0, and related bindings such as HTTP should be applied. Itsgoal is to constrain the use of these core specifications to agree on a set ofmessaging scenarios. Basic Security Profile is another set of guidance by WS-Ithat constrains core messaging scenarios for OASIS Web Service Security (WSS)specifically the SOAP Message Security specification and related token profilesfor passing username and password or X.509-based credentials. MTOM is theformally ratified specification for optimizing how opaque data is transmittedwith a SOAP message.

You can use BasicHttpBinding to migrate existing ASMX orWSE Web services leveraging these standards. Endpoints exposed over thisbinding can also be called by other legacy client technologies that don tunderstand SOAP 1.2 or WS-Addressing headers. Some typical scenarios forBasicHttpBinding include:

  • Supporting SOAP 1.1

  • UserName token support over SSL

  • Mutual certificate authentication

  • Sending large messages with MTOM

 

Supporting SOAP 1.1

BasicHttpBinding always serializes messages in SOAP 1.1format, so this binding is a natural choice for any communications that shouldbe based on that protocol. To expose a simple service over SOAP 1.1 without anysecurity enabled, use the defaults for BasicHttpBinding, as follows:

  

When clients call the service they don t pass any credentials,and messages aren t signed or encrypted which is the same result you get witha vanilla ASP.NET Web service.

 

UserName Token over SSL

Many Web services today require a username and passwordfor authentication, and SSL for service authenticationand message protection. Because BasicHttpBinding is not secure by default, you mustcustomize the binding to achieve this. Set the security mode toTransportWithMessageCredential and change the client credential type toUserName. Most frequently, the service also wants to authenticate and authorizethe username and password against a custom database and not the Windows domain.With WCF you associate a set of authentication and authorization behaviorssetting userNamePasswordValidationMode and principalPermissionMode toMembershipProvider and UseAspNetRoles, respectively. This tells WCF to use theconfigured ASP.NET membership and role providers. The complete configurationfor this scenario is shown in Figure 1.

                                                                                                                    

Figure 1: Serviceconfiguration for username over SSL with ASP.NET authentication andauthorization.

The IIS Web site hosting this service must have an SSLcertificate installed to support this scenario. Clients use an HTTPS endpointto reach the service, as is reflected in the client endpoint configuration:

  

In addition, clients must provide a username and passwordto the ClientCredentials property of the proxy:

WebServiceContractClient proxy = new WebServiceContractClient("Soap11UsernameTokenSSL");proxy.ClientCredentials.UserName.UserName = "username";proxy.ClientCredentials.UserName.Password = "password"; 

These credentials are serialized in a secure andinteroperable fashion according to the UserName Token Profile of OASIS WSS.

With SSL, messages are only protected from point-to-point,with no guarantees of protection all the way through to the applicationdestination if a proxy or intermediary service is present. Using messagesecurity to secure transfer protects messages across multiple hops end-to-endbut this scenario is not supported by BasicHttpProfile for UserNamecredentials. To achieve this, you can use WSHttpBinding (which I ll covershortly).

 

Mutual Certificate Authentication

Business partners may be required to authenticate using anX.509 certificate, which means enabling mutual certificate authenticationbetween client and service. Clients use a private key to sign outgoing messagesand decrypt responses from the service, and they authenticate the service basedon their service certificate using their public key to encrypt messages to theservice and to authenticate the signature of responses.

OASIS WSS describes how to sign and encrypt messages usingsecurity tokens so that the exchange is interoperable and end-to-end. Messagesecurity must be enabled to support this scenario, and the service must providea certificate and require clients to authenticate with certificates. Toconfigure BasicHttpBinding for this, specify Message security mode in the bindingconfiguration, supply a service certificate in the service behavior section,and require Certificate credentials instead of UserName (see Figure 2).

                                                                                                                                      

Figure 2: Mutualcertificate authentication using message security.

To configure the service certificate you add it to theservice behavior. Instead of using ASP.NET authentication, client certificatesare authenticated according to settings in the section. Based on the configuration in Figure 2, PeerTrust is used, which meansthat the corresponding public key for each trusted client certificate must beinstalled in the TrustedPeople store in the LocalMachine certificate store.

The client requires access to the service public key,which means either installing it to the client machine certificate store orincluding a base64-encoded copy of the certificate in the client endpointconfiguration. When you generate a proxy for a BasicHttpBinding endpoint, youmust manually add information about the service certificate. If you install thepublic key certificate to the client machine, you can provide a certificatereference in the section:

      

An alternate approach is to provide it with the endpointbehavior, along with the client s private key certificate (see Figure 3).

                                                                                                

Figure 3:Configuring certificates for the client endpoint.

Fortunately, when you add a service reference in WCF, abase64-encoded copy of the service certificate is placed in the clientconfiguration file as part of the section of the endpoint:

      

Clients can also specify certificates in code:

proxy.ClientCredentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My,X509FindType. FindBySubjectName, "SubjectKey");proxy.ClientCredentials.ServiceCertificate. SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "SubjectKey"); 

Mutual certificate authentication results in end-to-endmessage security according to OASIS WSS.

 

MTOM

In any of these BasicHttpBinding security scenarios youcan also optimize support for large messages using MTOM an interoperableencoding format for SOAP messages that reduces message size and parsingoverhead when dealing with binary data in a SOAP message. I won t get into thedetails of the format here, but you can configure the binding to use MTOMinstead of Text encoding (the default) with the message encoding setting:

 

MTOM encoding is orthogonal to security settings, so thiscan be used in conjunction with any of the other binding and behavioralsettings for the service. WSHttpBinding and WSFederationHttpBinding alsosupport MTOM encoding. For this to work, the client must also be configured forMTOM. Because MTOM is included in the WSDL for the service, the generatedclient configuration will automatically include the correct setting.

 

WSHttpBinding

WSHttpBinding allows you to expose WCF service endpointscompatible with more recent Web service stacks that support SOAP 1.2 andWS-Addressing in addition to other standards such as MTOM, Kerberos, and SAMLtoken profiles for WSS, WS-SecureConversation, WS-ReliableMessaging, andWS-AtomicTransaction. You can use WSHttpBinding to migrate services based onASMX with WSE that use these standards, while also supporting newer clienttechnology stacks that implement the most recent versions of eachspecification. Some typical scenarios for WSHttpBinding deployments include thefollowing:

  • Supporting SOAP 1.2 and WS-Addressing

  • UserName, Kerberos, Certificate, or SAML token authentication with end-to-end message security

  • Secure sessions with WS-SecureConversation

  • Reliable sessions with WS-ReliableMessaging

  • Distributed transactions with WS-AtomicTransaction

  • Sending large messages with MTOM

Supporting SOAP 1.2 and WS-Addressing

By default, WSHttpBinding serializes all messages using theSOAP 1.2 format with WS-Addressing headers included. To support these protocolson a simple anonymous service endpoint, you can customize WSHttpBinding anddisable security:

      

If you want a SOAP 1.2 endpoint without addressingheaders, you must resort to a custom binding, and explicitly set the messageversion:

         

 

Credential Support and Message Security

With WSHttpBinding you can send UserName credentials overSSL or use Certificate credentials for mutual authentication in the same waydiscussed for BasicHttpBinding. What s different is that messages will beserialized using SOAP 1.2 and include addressing headers. Another difference isthat WSHttpBinding has full support for OASIS token profiles, which meanssending any credentials, including UserName, Certificate, Windows/Kerberos, andSAML, with end-to-end message security.

With SSL, message protection is only appliedpoint-to-point, with no guarantees that the message will be encrypted all theway through to its final destination. Message security, on the other hand,protects messages across multiple hops.

OASIS WSS describes how to sign and encrypt messagingusing security tokens so that this end-to-end secure exchange is fullyinteroperable.

WSHttpBinding uses message security mode by default.Message security for non-Windows credentials requires that a servicecertificate be provided to authenticate the service and to facilitate messagetransfer protection. The behavior configuration for the service certificate isthe same as I discussed for BasicHttpBinding. One of the key differences withWSHttpBinding is that service credentials can be negotiated and by defaultnegotiation is enabled for the binding:

              

When negotiation is enabled the session key used formessage protection is negotiated through a series of calls to the servicetunneled through a protocol named WS-Trust. This exchange is built in to theWCF plumbing. It essentially saves the client from having access to the servicecertificate a priori for non-Windows credentials. For Windows credentials, nocertificate is required. The problem with negotiation is that although WS-Trustis interoperable, the negotiation protocols used are not. So, to provide aninteroperable endpoint today you would have to disable negotiation by settingnegotiateServiceCredentials to false. For non-Windows credentials, this meansthat one-shot message security according to OASIS WSS is used, and the client mustknow the service certificate. For Windows credentials, this requires thepresence of a Kerberos domain.

You can configure WSHttpBinding to use NTLM or Kerberos bysetting the credential type to Windows:

              

If a Kerberos domain is present, the token is serializedas Kerberos; otherwise, NTLM is used. When the client proxy is constructed, ituses the Windows token for the client application by default usually thelogged-in user. To specify an alternate credential, you can construct aNetworkCredential and assign it to the ClientCredentials reference before thechannel is constructed on the first call:

NetworkCredential credential = new NetworkCredential( "username", "password", "domain");proxy.ClientCredentials.Windows.ClientCredential = credential; 

WSHttpBinding also supports IssuedToken credentials suchas SAML tokens, but you should use WSFederationHttpBinding for this type ofcredential as it has more configuration options. This type of token alsoinvolves custom authorization.

 

Secure Sessions

Regardless of the credentials used to perform mutualauthentication, secure sessions can be enabled so that a session key isgenerated for multiple communications between client and service. This canreduce the overhead of each message, along with authentication overhead at theservice. By default, WSHttpBinding has secure sessions enabled. To disable it,use this configuration:

              

Secure sessions are implemented with WS-SecureConversationprotocol, which is interoperable with any technology stack that also implementsthe standard, including ASMX services using WSE. The standard is not yetratified, though it is under the OASIS WS-SX committee (along with WS-Trust). Agood number of platforms already support both of these standards so thatinteroperability can be achieved but you may also need to provide serviceendpoints that disable this, to reach a wider client base.

 

Reliable Sessions with WS-ReliableMessaging

Reliable sessions make it possible for messages to survivetransient network failure and thus provide some level of delivery assurance. Bydefault, this protocol is disabled in WSHttpBinding; however, it can be enabledwith the following configuration:

                 

You can also configure support for ordered messages andsession activity timeout (which defaults to 10 minutes). When reliable sessionsare enabled, secure sessions must also be enabled. Thus, platforms that supportWS-ReliableMessaging are likely to support WS-SecureConversation.WS-ReliableMessaging is not yet ratified, but it is under review with the OASISWS-RM committee, and has been implemented in several leading platforms in itscurrent state. Like with WS-SecureConversation, you may need to provideendpoints without reliable sessions to reach a wider client base.

 

Transactions with WS-AtomicTransaction

Distributed transactions over HTTP are also supported withWSHttpBinding. Transactions warrant a longer discussion that I won t embark onhere. Suffice it to say that the WS-AtomicTransaction specification, underreview with the OASIS WS-TX committee, makes it possible for disparate systemsto participate in distributed transactions over HTTP. This is another protocolthat is not yet ratified or widely implemented, but you can expect to exposeendpoints that support it for those clients that can leverage it.

 

Conclusion

Deploying WCF Web services for your ASP.NET applicationscan be as simple as your typical ASMX service, using BasicHttpBinding defaults.You can also support commonly implemented security standards by choosingBasicHttpBinding or WSHttpBinding with UserName, Windows, or Certificatecredentials without negotiation, secure sessions, reliable messaging, ortransactions. For services distributed over HTTP behind the firewall, or forWCF to WCF scenarios, or to support platforms that have implemented emergingstandards for security and reliability, you can leverage WSHttpBinding andenable these features. I ll discuss these features in greater detail in futurecolumn entries.

The sample code accompanyingthis article is available for download.

 

MicheleLeroux Bustamante is Chief Architect at IDesign Inc., Microsoft RegionalDirector for San Diego, Microsoft MVP for Connected Systems, and a BEATechnical Director. At IDesign Michele provides training, mentoring, andhigh-end architecture consulting services, specializing in scalable and secure.NET architecture design, globalization, Web services, and interoperabilitywith Java platforms. She is a board member for the International Association ofSoftware Architects (IASA), a frequent conference presenter, conference chairof SD s Web Services and Web Development tracks, and a frequently publishedauthor. Michele recently completed the book LearningWCF, published by O Reilly (book blog: http://www.thatindigogirl.com). Reachher at http://www.idesign.net or http://www.dasblonde.net.

 

Additional Resources

WCF Home: http://wcf.netfx3.com

OASIS: http://www.oasis-open.org

W3C: http://www.w3c.org

WS-I: http://www.ws-i.org

Michele s blog: http://www.dasblonde.net

Michele s WCF book: http://www.thatindigogirl.com

IDesign: http://www.idesign.net

 

 

 

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like