WCF Security Implementation

While working on client server environment, security of the data or message is very important. Before doing anything or transmitting your data please ensure security measures have been taken. Need to do all the efforts to incorporate security.
Now we are going to talk about WCF security. The inbuilt provision is provided by Microsoft from version .Net framework 3.0 onwards.
Windows Communication Foundation (WCF) is a secure, reliable, and scalable messaging platform for the .NET Framework 3.0
As WCF supports various protocols i.e. TCP, HTTP, and MSMQ, user must be sure enough to take necessary steps to guard your message and also must establish security policies for protecting messages and for authenticating and authorizing calls. WCF provides a very easy and rich configurable environment to implement security.
WCF supports following securities:
  • Message
  • Transport
  • TransportWithMessageCredential

Message Security

Message security uses the WS-Security specification to secure messages. The message is encrypted using the certificate and can now safely travel over any port using plain http. It provides end-to-end security. Because message security directly encrypts and signs the message, having intermediaries does not break the security. Message security can be used when the client is deployed on internet.

Transport Security

Transport security is 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. Typically, you can use transport security when your client is deployed within an intranet, as it provides point-to-point security and better performance compared to message security.


This we can call a mixture of both Message and Transport security implementation. Credentials are passed with the message and message protection and server authentication are provided by the transport layer.

Implementation of TransportWithMessageCredential

Step 1: Create certificate
  • We need to create both Server and Client certificates.
    makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=CertTestServer -sky exchange –pe
    makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=CertTestClient -sky exchange –pe

  • In order to do so, you need to install SDK tools from Microsoft. If you have already installed, you may find makecert.exe in "C:\Program Files\Microsoft SDKs\Windows\v5.1\Bin".

  • Both the certificates are created but they are not under trusted category. For that Open Microsoft Management Console. Go to Run --> execute "MMC".

  • Now console is opened, go to File --> Click on "Add/Remove Snap-in" --> now select Certificates on left pane and click "Add" button.

  • Now, certificates were added to console view. There will be different categories of certificates. If you open Personal folder, we can find the certificates we created in earlier steps. Copy them to Trusted People folder. Close the console.
Step 2: Web.config configuration
  1. <bindings>  
  2.   <wsHttpBinding>  
  3.     <binding name="wsHttpEndpointBinding">  
  4.       <security mode="TransportWithMessageCredential">  
  5.         <message clientCredentialType="Certificate" /> //user can use username as well  
  6.          </security>  
  7.     </binding>  
  8.   </wsHttpBinding>  
  9. </bindings>  
  10. <behaviors>  
  11.   <serviceBehaviors>  
  12.     <behavior name="MessageSecurity.Service1Behavior">  
  13.       <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  14.        <serviceMetadata httpGetEnabled="true" />  
  15.          <!-- 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 -->  
  16.          <serviceDebug includeExceptionDetailInFaults="false" />  
  17.          <serviceCredentials>  
  18.            <clientCertificate>  
  19.             <authentication certificateValidationMode="PeerTrust" />  
  20.              </clientCertificate>  
  21.               <serviceCertificate findValue="CertTestServer" storeLocation="CurrentUser" storeName="TrustedPeople" x509FindType="FindBySubjectName" />  
  22.               <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MessageSecurity.AuthenticationHelper,MessageSecurity " />  
  23.          </serviceCredentials>  
  24.        <!--<serviceDebug includeExceptionDetailInFaults="False"/>-->  
  25.     </behavior>  
Step 3: Code IService1 (interface)
Code IService 
  1. public class Service1: IService1   
  2. {  
  3.     #region IService1 Members  
  5.     public List < Book > GetAllBooks()   
  6.     {  
  7.         List < Book > lstBook = new List < Book > ();  
  8.         //Checking for authorization  
  9.         if (OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.IsAuthenticated == false)   
  10.         {  
  11.             throw new SecurityException();  
  12.         } else   
  13.         {  
  14.             //Using LINQ to read the XML  
  15.             var xdoc = XDocument.Load(@"D:\Nishant\Project\MessageSecurity\MessageSecurity\Book.xml");  
  16.             //Getting all details of Book....  
  17.             var units = from u in xdoc.Descendants("book")  
  18.             select new   
  19.             {  
  20.                 Id = (string) u.Element("author"),  
  21.                     Title = (string) u.Element("title"),  
  22.                     Genre = (string) u.Element("genre"),  
  23.                     Price = (string) u.Element("price"),  
  24.                     PublishDate = (string) u.Element("publishdate"),  
  25.                     Description = (string) u.Element("description")  
  26.             };  
  27.             //Looping and storing the same in Book object  
  28.             foreach(var unit in units)   
  29.               {  
  30.                 // GOD IntelliSense!!!!!! saves us..(:  
  31.                 Book book = new Book();  
  32.                 book.Author = unit.Id;  
  33.                 book.Title = unit.Title;  
  34.                 book.Genre = unit.Genre;  
  35.                 book.Price = unit.Price;  
  36.                 book.PublishDate = unit.PublishDate;  
  37.                 book.Description = unit.Description;  
  38.                 //Adding the book to list of books....  
  39.                 lstBook.Add(book);  
  40.             }  
  41.         }  
  42.         return lstBook;  
  43.     }  
  45.     public string GetData(int value)   
  46.     {  
  47.         return string.Format("Comunication through Message Security: {0}", value);  
  48.     }#  
  49.     endregion  
  50. }  
Create a New Project and add the service reference mentioned below:
  1. ServiceReference2.Service1Client objservice = new Test.ServiceReference2.Service1Client();  
  2. ServiceReference2.Book[] lstBook = objservice.GetAllBooks();  
And use the code as mention in the Main method.

Similar Articles