WCF FAQ Part 3 - 10 Security Related FAQ

Introduction and Goal

 
In this article we will start with transport and message security understanding. We will then see simple code samples of how to implement transport and message security using WsHTTP bindings. We will also see what is the difference between 'BasicHttpBinding' and 'WsHttpBinding' with the help of a simple source code. WCF security is a huge topic by itself, but we are sure with this article you will get a quick start of how to go about WCF security.
 
I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML etc. Feel free to download these FAQ PDF's from my site http://www.questpond.com/
 
WCF FAQ Part 1 and 2 series
 
WCF FAQ Part 1   :- This is a 20 question FAQ for beginners which explains basic concepts of WCF like End points , contracts and bindings. It also discusses about various hosting methodologies of WCF service. The article finally ends talking about bindings and one ways operations in WCF.
 
WCF FAQ Part 2 :- This FAQ covers 10 questions which talks about concepts like duplex contracts , hosting WCF on different protocols , MSMQ bindings , transaction isolation levels and two way communication. The article finally ends talking about two queues volatile and dead letter queu
 

What are the core security features that WCF addresses?

 
There are four core security features that WCF addresses:-
 
Confidentiality: This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.
Integrity: This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering.
Authentication: This feature verifies who the sender is and who the receiver is.
Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.
 
1.JPG 
 

What is transport level and message level security?

 
When we talk about WCF security there are two aspects, the first is the data and the second is the medium on which the data travels i.e. the protocol. WCF has the ability to apply security at the transport level (i.e. protocol level) and also at message level (i.e. data).
 
222.jpg 
Figure: - Transport and Message level security
 
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it's more of using the existing security mechanism provided by the protocol.
 
Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.
 

For which bindings are transport, message and mixed mode supported? 

 
Note :- The below table is taken from book Pro WCF: Practical Microsoft SOA Implementation -- Chris peiris and Denis mulder  Apress 2007
 
Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It's nothing but combination of transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is nothing but message security and HTTPS is a transport mode. In a combination they form mixed mode.
 
Binding Transport Mode? Message Mode? Mixed Mode?
BasicHttpBinding Yes Yes Yes
WsHttpBinding Yes Yes Yes
WsDualHttpBinding No Yes No
NetTcpBinding Yes Yes Yes
NetNamedPipeBinding Yes No No
NetMsmqBinding Yes Yes No
MsmqIntegrationBinding Yes No No
 

So what are the scenarios, advantages and disadvantages of transport VS message security?

 
 
Transport
Message
Scenarios when we should be using one of them
When there are no intermediate systems in between this is the best methodology.  
If it's an intranet type of solution this is most recommended methodology.
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.
Advantages
  • Does not need any extra coding as protocol inherent security is used.
  • Performance is better as we can use hardware accelerators to enhance performance.
  • There is lot of interoperability support and communicating clients do not need to understand WS security as it's built in the protocol itself.
 
  • Provides end to end security as it's not dependent on protocol. Any intermediate hop in network does not affect the application.
  • Supports wide set of security options as it is not dependent on protocol. We can also implement custom security.
Disadvantages
  • As it's a protocol implemented security so it works only point to point.
  • As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.
  • Needs application refactoring to implement security.
  • As every message is encrypted and signed there are performance issues.
  • Does not support interoperability with old ASMX webservices/
 
3.JPG 
Figure: - Route paths
 

Can you explain a simple example of how to implement transport security?

 
Let's make a simple sample which will demonstrate how we can use transport security using WsHttp binding with HTTPS security.
 
Step 1 - Create a simple service using WCF project
 
The first step is to create a simple WCF project. So click on new project and select WCF service project. By default WCF project creates a default function 'GetData()'. We will be using the same function for this sample.
  1. public class Service1 : IService1   
  2. {   
  3.     public string GetData(int value)   
  4.     {   
  5.         return string.Format("You entered: {0}", value);   
  6.     }   
  7.     public CompositeType GetDataUsingDataContract(CompositeType composite)   
  8.     {   
  9.         if (composite.BoolValue)   
  10.         {   
  11.             composite.StringValue += "Suffix";   
  12.         }   
  13.         return composite;   
  14.     }   
  15.  

Step 2 - Enable transport level security in the web.config file of the service

Next step is to enable transport security in WsHttp binding. This is done using the 'Security' XML tag as shown in the below code snippet.
  1. <bindings>  
  2.     <wsHttpBinding>  
  3.         <binding name="TransportSecurity">  
  4.             <security mode="Transport">  
  5.                 <transport clientCredentialType="None"/>  
  6.             </security>  
  7.         </binding>  
  8.     </wsHttpBinding>  
  9. </bindings>

Step 3 - Tie up the binding and specify HTTPS configuration

We need now tie up the bindings with the end points. So use the 'bindingConfiguration' tag to specify the binding name. We also need to specify the address where the service is hosted. Please note the HTTS in the address tag.
 
Change 'mexHttpBinding' to 'mexHttpsBinding' in the second end point.
  1. <service name="WCFWSHttps.Service1" behaviorConfiguration="WCFWSHttps.Service1Behavior">  
  2.     <!-- Service Endpoints -->  
  3.     <endpoint address="https://localhost/WCFWSHttps/Service1.svc" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="WCFWSHttps.IService1"/>  
  4.     <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>  
  5. </service>
In the 'serviceMetadata' we also need to change 'httpGetEnabled' to 'httpsGetEnabled'.
  1. <serviceBehaviors>........ .........  
  2.     <serviceMetadata httpsGetEnabled="true"/> ......... .........  
  3. </serviceBehaviors>  
Step 4 - Make the web application HTTPS enabled
 
Now that we are done with the WCF service project creation and the necessary configuration changes are done. It's time to compile the WCF service project and host the same in IIS application with HTTPS enabled.
 
We will be using 'makecert.exe' which is a free tool given by Microsoft to enable HTTPS for testing purpose. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.
 
You can get the same from "C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin" or you can also get it from windows SDK.
 
You can type the below thing through your dos prompt on "C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin". Please note "compaq-jzp37md0" is the server name so you need to replace with your PC name. 
 
makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
 
If you run the same through your command prompt you should get a succeeded message as shown below. 

4.jpg

Now it's time to assign this certificate to your IIS website. So go to IIS properties , click on directory security tab and you should see server certificate tab.
 
5.jpg 
 
So click on the server certificate tab and you will then be walked through an IIS certificate wizard. Click 'Assign a existing certificate' from the wizard.
 
6.jpg 
 
You can see a list of certificates. The "compaq-jzp37md0" certificate is the one which we just created using 'makecert.exe'.
 
7.jpg 
 
Now try to test the site without 'https' and you will get an error as shown below….That means your certificate is working.
 
8.jpg 
 
Do not forget to enable IIS anonymous access.
 
Step 5 - Consume the service in a web application
 
It's time to consume the service application in ASP.NET web. So click on add service reference and specify your service URL. You will shown a warning box as shown in the below figure. When we used makecert.exe we did not specify the host name as the service URL. So just let it go.
 
9.jpg 
 
Step 6 - Suppress the HTTPS errors
 
'makecert.exe' creates test certificates. In other words it's not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we have created a function called as 'IgnoreCertificateErrorHandler' which return true even if there are errors. This function is attached as a callback to 'ServicePointManager.ServerCertificateValidationCallback'.
 
In the same code you can also see service consuming code which calls the 'GetData' function.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using WebApplicationConsumer.ServiceReference1;  
  8. using System.Net;  
  9. using System.Net.Security;  
  10. using System.Security.Cryptography.X509Certificates;  
  11. namespace WebApplicationConsumer   
  12. {   
  13.     public partial class _Default : System.Web.UI.Page   
  14.     {   
  15.         protected void Page_Load(object sender, EventArgs e)   
  16.         {   
  17.             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);   
  18.             Service1Client obj = new Service1Client();   
  19.             Response.Write(obj.GetData(12));   
  20.         }   
  21.         public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)   
  22.         {   
  23.             return true;   
  24.         }   
  25.     }   
  26. }   
Step 7 - Enjoy success
 
Now to the easiest step, compile you ASP.NET client and enjoy success.
 
10.jpg 
 

Can you show a simple example of message level security?

 
Let's do a simple example of message security using Wshttp with X509 certificates.
 
Step 1 - Create client and server certificates
 
Create two certificates one for the server and the other for the client using makecert.exe. You can get makecert.exe from "C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin" folder. So you can goto dos prompt and run the below command snippet.
 
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCfServer -sky exchange -pe
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfClient -sky exchange -pe
 
Below is a detailed explanation of various attributes specified in the 'makecert.exe'. 
 
Attribute
Explanation
-sr
Specifies the registry location of the certificate store. The SubjectCertStoreLocation argument must be either of the following:
currentUser
Specifies the registry location HKEY_CURRENT_USER.
localMachine
Specifies the registry location HKEY_LOCAL_MACHINE.
-ss
Specifies the name of the certificate store where the generated certificate is saved.
-a
Specifies the algorithm. Can be either MD5 or SHA1.
-n
Specifies a name for the certificate. This name must conform to the X.500 standard. The simplest method is to use the "CN=MyName" format.If the /n switch is not specified; the default name of the certificate is "Joe's Software Emporium".
-sky
Specifies how will be the key type. Can be either exchange or signature.
-pe
This makes the key exportable.
 
Note: - Makecert.exe is a free tool provided by Microsoft which helps to create X.509 certificate that is signed by a system test root key or by another specified key. This is a test certificate and not a real one and should not be used for production purpose. For production buy proper certificates from Thawte, Verisign, GeoTrust etc.
 
Currently we have specified that we want to create the client key with 'WcfClient' name and server key with 'WCFServer'. The certificates should be created for the current user and should be exportable.
 
Once you run the command you should see the 'Succeeded' message as shown in the below figure. Below figure shows keys created for both server and client.
 
11.jpg 
 
Step 2 - Copy the certificates in trusted people certificates
 
Go to start  run and type MMC and press enter. You will be popped with the MMC console. Click on file  Add/remove snap-in.
 

12.jpg

You will be popped up with a Add/Remove Snap-in, click on the add button, select certificates and select 'My user Account'.
 
You can see the certificates created for client and server in the personal certificates folder. We need to copy those certificates in trusted people  certificates folder.
 
13.jpg 
 
Step 3 - Specify the certification path and mode in the WCF service web.config file
 
Now that we have created both the certificates we need to refer these certificates in our WCF project.
 
So we have created two projects one which has the WCF service and the other project is a web application which will consume the WCF service.
 
14.jpg 
 
Let's open the web.config file of the WCF service and enter two important things:-
 
-> Where the certificate is stored, location and how WCF application should find the same. This is defined using 'serviceCertificate' tag as shown in the below snippet.
-> The 'certificationvalidationmode' defines how client certificates will be authenticated.
 
Certification validation mode
Description
Chain trust
In this situation the client certificate is validated against the root certificate.
Peer trust
PeerTrust ensures that the public key portion of the certificate is in the Trusted People certificate folder on the clients computer
ChainORPeertrust
This is just a OR condition for both chain and peer.
 
The above two points is clubbed together and entered in the web.config file of the WCF service.
  1. <serviceCredentials>  
  2.     <clientCertificate>  
  3.         <authentication certificateValidationMode="PeerTrust"/>  
  4.     </clientCertificate>  
  5.     <serviceCertificate findValue="WCfServer" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName" />  
  6. </serviceCredentials>  
Step 4 - Define bindings 
 
Now that we have defined our certificates and authentication type we need to define that the authentication values will be sent through message using certificates. You can see we have defined the 'WsHttpBinding' with message attribute specifying that the WCF client needs to send a certificate for validation.
  1. <bindings>  
  2.     <wsHttpBinding>  
  3.         <binding name="wsHttpEndpointBinding">  
  4.             <security>  
  5.                 <message clientCredentialType="Certificate" />  
  6.             </security>  
  7.         </binding>  
  8.     </wsHttpBinding>  
  9. </bindings>  
Step 5 - Tie up the bindings with end point
 
Once done we need to tie up this binding with the end point. This is done by using 'bindingConfiguration' tag as shown in the below code snippet.
  1. <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">  
Step 6 - Make your web application client for consuming the WCF service 
 
That's all we need to from the WCF service perspective. So compile the WCF service and reference the same in the ASP.NET web application using 'Service reference'. Below is the code snippet where we have referenced the service and called the 'GetData' function of the service/
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5. using System.Web.UI;   
  6. using System.Web.UI.WebControls;   
  7. using WebConsumer.ServiceReference1;  
  8.   
  9. namespace WebConsumer   
  10. {   
  11.     public partial class _Default : System.Web.UI.Page   
  12.     {   
  13.         protected void Page_Load(object sender, EventArgs e)   
  14.         {   
  15.             Service1Client obj = new Service1Client();  
  16.             Response.Write(obj.GetData(12));  
  17.         }  
  18.     }  
  19. }  
Now if you try to run the client i.e. the web application as it is you should get an error as shown below. The error clearly indicates you can use the WCF service until you do not provide the client certificate.
 
15.jpg 
 
Step 7 - Define certificates in WCF client
 
So let's start the process of defining certificates in the WCF client. The way we have defined authentication certification mode and the path of the certificate, in the same way we need to define it for WCF client. You can see we have defined the authentication mode as 'peertrust' and we have specified the client certificate name as 'WcfClient'.
  1. <behaviors>  
  2.     <endpointBehaviors>  
  3.         <behavior name="CustomBehavior">  
  4.             <clientCredentials>  
  5.                 <clientCertificate findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />  
  6.                 <serviceCertificate>  
  7.                     <authentication certificateValidationMode="PeerTrust"/>  
  8.                 </serviceCertificate>  
  9.             </clientCredentials>  
  10.         </behavior>  
  11.     </endpointBehaviors>  
  12. </behaviors>  
Step 8 - Tie up the behavior with end point on WCF client 
 
We need to tie up the above defined behavior with the end point. You can see we have bounded the behavior using 'behaviorConfiguration' property. We also need to specify that the DNS value will be 'WcfServer' which your server certificate name.
  1. <client>  
  2.     <endpoint address="http://localhost:1387/Service1.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1" name="WSHttpBinding_IService1" behaviorConfiguration="CustomBehavior">  
  3.         <identity>  
  4.             <dns value="WcfServer" />  
  5.         </identity>  
  6.     </endpoint>  
  7. </client>  
Step 9 - Enjoy your hard work
 
Once we are done you can run the ASP.NET web and you should see the below display.
 
16.jpg 
 

What is the difference between BasicHttpBinding and WsHttpBinding?

 
If we want to summarize in one sentence the difference between 'WsHttpBinding' and 'BasicHttpBinding' is the 'WsHttpBinding' supports 'WS-*' specification. WS-* specifications are nothing but standards to extend web service capabilities.
 
Below is a detailed comparison table between both the entities from security, compatibility, reliability and SOAP version perspective.
 
Criteria
BasicHttpBinding
WsHttpBinding
Security support
This supports the old ASMX style i.e WS-BasicProfile 1.1.
This exposes web services using WS-* specifications.
Compatibility
This is aimed for clients who do not have .Net 3.0 installed and it supports wider ranges of client. Many of clients like Windows 2000 still do not run .NET 3.0. So older version of .NET can consume this service.
As its built using WS-* specifications it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.
Soap version
SOAP 1.1
SOAP 1.2 and WS-Addressing specification.
Reliable messaging
Not supported. In other words if a client fires two or three calls you really do not know they will return back in the same order.
Supported as it supports WS-* specifications.
Default security options
By default there is not security provided for messages when the client calls happen. In other words data is sent as plain text.
As WsHttBinding supports WS-* it has WS-Security enabled by default. So the data is not sent in plain text.
Security options
  • None
  • Windows â€" default authentication.
  • Basic
  • Certificate
  • None
  • Transport.
  • Message.
  • Transport with message credentials.
 
One of the biggest differences you must have noticed is the security aspect. By default 'BasicHttpBinding' sends data in plain text while 'WsHttpBinding' sends in encrypted and secured manner. To demonstrate the same let's make two services one using 'BasicHttpBinding' and the other using 'WsHttpBinding' and then let's see the security aspect in a more detailed manner.
 
We will do a small sample to see how 'BasicHttpBinding' sends data in plain text format and how 'WsHttpBinding' encrypts data.
 
Note :- By Default security is not enabled on 'BasicHttpBinding' for interoperability purpose. In other words it like our old webservice i.e. ASMX. But that does not mean we cannot enable security in 'BasicHttpBinding'. Sometimes back we had a written a article on how to enable security on 'BasicHttpBinding' http://www.codeproject.com/KB/WCF/WCFBasicHttpBinding.aspx
 

Can you show the security differences between BasicHttpBinding VS WsHttpBinding?

 
In order to understand the security differences between both these entities we will do a small project. In this project we will create two WCF service one service using 'BasicHttpBinding' and the second service using 'WsHttpBinding'.
 
17.jpg 
 
Step 1 - So let's first create a simple service using 'BasicHttpBinding'. For that we just a create a simple WCF project and then modify the 'ServiceModel' element as shown below. You can see in the 'endpoint' tag we have specified 'basicHttpBinding' as the protocol.
  1. <system.serviceModel>  
  2.     <services>  
  3.         <service name="WCFBasicHttpBinding.Service1" behaviorConfiguration="WCFBasicHttpBinding.Service1Behavior">  
  4.             <!-- Service Endpoints -->  
  5.             <endpoint address="" binding="basicHttpBinding" contract="WCFBasicHttpBinding.IService1">  
  6.                 <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. -->  
  7.                 <identity>  
  8.                     <dns value="localhost"/>  
  9.                 </identity>  
  10.             </endpoint>  
  11.             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  12.         </service>  
  13.     </services>  
  14.     <behaviors>  
  15.         <serviceBehaviors>  
  16.             <behavior name="WCFBasicHttpBinding.Service1Behavior">  
  17.                 <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  18.                 <serviceMetadata httpGetEnabled="true"/>  
  19.                 <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->  
  20.                 <serviceDebug includeExceptionDetailInFaults="false"/>  
  21.             </behavior>  
  22.         </serviceBehaviors>  
  23.     </behaviors>  
  24. </system.serviceModel>   
Step 2 - We also need to create one more service using 'WsHttpBinding'. For that you do not need to anything special as such. By default WCF project is created using 'WsHttpBinding'. Below is how the Web.config file looks like. You can see how the endpoint tag is using 'wsHttpBinding'.
  1. <system.serviceModel>  
  2.     <services>  
  3.         <service name="WCFWsHttpBindingHttps.Service1" behaviorConfiguration="WCFWsHttpBindingHttps.Service1Behavior">  
  4.             <!-- Service Endpoints -->  
  5.             <endpoint address="" binding="wsHttpBinding" contract="WCFWsHttpBindingHttps.IService1">  
  6.                 <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. -->  
  7.                 <identity>  
  8.                     <dns value="localhost"/>  
  9.                 </identity>  
  10.             </endpoint>  
  11.             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  12.         </service>  
  13.     </services>  
  14.     <behaviors>  
  15.         <serviceBehaviors>  
  16.             <behavior name="WCFWsHttpBindingHttps.Service1Behavior">  
  17.                 <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  18.                 <serviceMetadata httpGetEnabled="true"/>  
  19.                 <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->  
  20.                 <serviceDebug includeExceptionDetailInFaults="false"/>  
  21.             </behavior>  
  22.         </serviceBehaviors>  
  23.     </behaviors>  
  24. </system.serviceModel>   
Step 3 - We will not be creating any new methods in both the services. We will just use the default code created by the WCF template. So both these services will have a 'GetData' function which returns a string. The 'GetData' function is a default function created WCF project.
  1. public class Service1 : IService1   
  2. {   
  3.     public string GetData(int value)   
  4.     {   
  5.         return string.Format("You entered: {0}", value);   
  6.     }   
  7.     public CompositeType GetDataUsingDataContract(CompositeType composite)   
  8.     {   
  9.         if (composite.BoolValue)   
  10.         {   
  11.             composite.StringValue += "Suffix";   
  12.         }   
  13.         return composite;   
  14.     }   
  15. }  
Step 4 - Now that out services are created we need to create a client which will consume this service. So we have created a simple web application and we have added two references one is a service reference i.e. 'WsHttpBinding' and the second is a web reference i.e. 'BasicHttpBinding'. Please note when you right click to add reference you need to use the 'Add service reference' to add 'WsHttpService' and you need to add web reference for 'BasicHttpBinding'.
 
18.jpg 
 
We will add two buttons on the default aspx page. One button will call the http service and the other will call the wshttp service. Below is how the function 'GetData' is called in both the button clicks.
 
19.jpg 
 
Step 5 - So now we are ready with the complete project it is time to sniff and see how data is transported between client and the service in both the scenarios. So let's download a simple http data recorder from http://www.ieinspector.com/httpanalyzer/download.html  . We will then click both the buttons one by one and record the data transfer using httpanalyzer. You can see the posted data is in simple plain XML format for basic http protocol and it's in an encrypted format for wshttp protocol.
 
20.jpg 
 

When should we use WsHttp as compared to BasicHttp?

 
If you are looking for back ward compatibility and to support lot of clients then basic http binding is the way to go or else WsHttp is the great way to start if you are seeing your clients made in .NET 3.0 and above.
 

How can we enable windows authentication on WCF using 'BasicHttpBinding'?

 
Step 1 - Create a project of WCF service application as shown in the below figure.
 
21.jpg 
 
Circle WCF service application Select this
 
By default the WCF project creates a class file which has 'GetData' function. This function takes in a number values and displays a explanatory sentence like 'You entered 1 value' , in case you have entered '1'.
  1. public class Service1 : IService1   
  2. {   
  3.     public string GetData(int value)   
  4.     {   
  5.         return string.Format("You entered: {0}", value);   
  6.     }   
  7. }  
Step 2 - When we create a WCF service application it also has a web.config file associated with it. So open the web.config file and ensure that authentication mode is windows.
  1. <authentication mode="Windows" />  
Step 3 - The third step is to define the bindings and the transport type. To define the bindings we need to enter 'basicHttpBinding' element inside the 'bindings' XML tag. We also need to define the 'clientCredentialType' as windows.
  1. <system.serviceModel>  
  2.     <bindings>  
  3.         <basicHttpBinding>  
  4.             <binding name="BasicHttpEndpointBinding">  
  5.                 <security mode="TransportCredentialOnly">  
  6.                     <transport clientCredentialType="Windows" />  
  7.                 </security>  
  8.             </binding>  
  9.         </basicHttpBinding>  
  10.     </bindings>  
  11.     <services>......... .........  
  12. </system.serviceModel>  
Step 4 - Now the bindings defined needs to be associated with service interface i.e. 'service1'. So we need to modify the services elements as shown below. You can note that we have defined a end point which has the binding association.
  1. <system.serviceModel>........ ........ ........  
  2.     <services>  
  3.         <service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">  
  4.             <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpointBinding" name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">  
  5.                 <identity>  
  6.                     <dns value="localhost" />  
  7.                 </identity>  
  8.             </endpoint>  
  9.         </service>  
  10.     </services> ......... ......... ......... .........  
  11. </system.serviceModel>  
So over all your <system.serviceModel> XML part as whole with bindings and services is a shown below.
  1. <system.serviceModel>  
  2.     <bindings>  
  3.         <basicHttpBinding>  
  4.             <binding name="BasicHttpEndpointBinding">  
  5.                 <security mode="TransportCredentialOnly">  
  6.                     <transport clientCredentialType="Windows" />  
  7.                 </security>  
  8.             </binding>  
  9.         </basicHttpBinding>  
  10.     </bindings>  
  11.     <services>  
  12.         <service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">  
  13.             <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpEndpointBinding" name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">  
  14.                 <identity>  
  15.                     <dns value="localhost" />  
  16.                 </identity>  
  17.             </endpoint>  
  18.         </service>  
  19.     </services>  
  20.     <behaviors>  
  21.         <serviceBehaviors>  
  22.             <behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">  
  23.                 <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  24.                 <serviceMetadata httpGetEnabled="true"/>  
  25.                 <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->  
  26.                 <serviceDebug includeExceptionDetailInFaults="false"/>  
  27.             </behavior>  
  28.         </serviceBehaviors>  
  29.     </behaviors>  
  30. </system.serviceModel>  
Step 5 - Go to IIS properties and click on security tab and ensure that anonymous access is disabled and only windows authentication is enabled.
 
22.jpg 
 
Step 6 - We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication.
 
23.jpg 
 
Step 7 - So let's consume this WCF services. So add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.
 
24.jpg 
 
Step 8 - Type in the following code snippet in your page load. So add the namespace reference and call the method 'GetData'. The most important step to note is the credential supplied. 'DefaultCredentials' passes the current windows identity to the WCF service.
 
25.jpg 
 
If you execute the service you should get the following display as shown below.
 
26.jpg 
 
You can try commenting the below code in your client in other words we are not passing any credentials.
  1. obj.Credentials = System.Net.CredentialCache.DefaultCredentials;  
Now if you execute you should get the below error stating that this is a unauthorized call.
 
27.jpg 
 
Source Code
 
Whatever code we have discussed in the above FAQ. You can download the Source Code  from the link at bottom  of this article
 
Next >> WCF Tracing FAQ 


Similar Articles