WCF - Authentication and Authorization in Enterprise Architecting

In this article, I am going to show how to use Authorization and Authentication using a WCF service in Enterprise Architecting standards. This article is of Advanced WCF concepts. I am using an error driven approach for better experience with the problems and the solutions.
 
The core aspects we cover here are:
  • WCF
  • ASP.NET Authentication Service
  • Custom Authentication
  • HTTP Cookies
  • Authorization PrincipalPermission Attribute
  • Thread CurrentPrincipal
  • Message Interceptors
You will be wondering what the above are. In a quick summary the following are the activities involved.
  1. Create a WCF Service Application
  2. Add an AuthenticationService.svc reusing ASP.NET Authentication Service
  3. Create User Validator class
  4. Enable Custom Authentication in Global.asax
  5. Return Cookie if valid User
  6. Modify service configuration
  7. Try accessing the Authentication Service in Browser
  8. Create a UtilityService.svc with one method named GetData(int)
  9. Decorate the GetData(int) with PrincipalPermission attribute for Authorized Access only
  10. Decorate UtilityService class with AspNetCompatibilityRequirements attribute
  11. Set Utility Service constructor to set CurrentPrincipal from cookie
  12. Create the client application and add references to both services
  13. Create Authentication Service instance and invoke the Login() method
  14. Receive the cookie and store it
  15. Create a UtilityService instance and invoke GetData()
  16. Attach the Cookie to the UtilityService client
  17. Test the application and ensure the proper functioning
  18. Move the cookie attaching code to Interceptors in the Client Application
  19. Move the identity setting code to Interceptors in the Service Application
  20. Modify the service-side code to include Role instead of Name
  21. Use Encrypted Ticket for storing User Name and Roles
  22. Retest the Application
Authentication and Authorization
 
Before starting, we should have a clear understanding of Authentication and Authorization:
 
WCF1.jpg 
 
So to simplify, Authentication proves who the user is using his/her credentials or certificates.
 
Authorization deals with the rights the user has. For example, the Admin user will have Read, Write, Delete privileges but an ordinary Clerk will have Read permissions.
 
In WCF we are using the Membership infrastructure of ASP.NET to implement Authentication and Authorization.
 
Now we can start with the steps above.
 
Step 1: Create a WCF Service Application:
 
WCF2.jpg 
 
Step 2: Add an AuthenticationService.svc reusing ASP.NET Authentication Service.
 
Add a new WCF Service and name it AuthenticationService.svc. Delete the associated files since we are going to expose the ASP.NET Authentication Service.
  1. Delete AuthenticationService.cs
  2. Delete IAuthenticationService.cs
Replace the contents of AuthenticationService.svc with the following:
  1. <%@ ServiceHost   
  2.   Language="C#"  
  3.   Service="System.Web.ApplicationServices.AuthenticationService"   
  4.   Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>  
Here we are exposing System.Web.ApplicationServices.AuthenticationService through the svc file. The associated namespace is referred to our project by default.
 
The Authentication Service supports the following methods:
  • Login()
  • Logout()
  • ValidateUser()
Each of these methods work with the Membership Provider to perform the functionalities. We can also customize these aspects by providing our own database of user credentials and controlling the cookie creations.
 
Step 3: Create User Validator class
 
The Authentication Service will be receiving User Name and Password. We need to validate this with a Custom Provider. (We are not using ASP.NET Membership provider here.)
 
The following is the class definition of it. For the time being, we are hardcoding a user name as tom and password as chicago12.
  1. public class UserValidator  
  2. {  
  3.     public bool IsUserValid(string userName, string password)  
  4.     {  
  5.         bool result = (userName == "tom") && (password == "chicago12");  
  6.    
  7.         return result;  
  8.     }  
  9. }  
(Later in real projects you can change this single class to connect to a database to validate the user name and password)
 
Step 4: Enable Custom Authentication in Global.asax
 
Add a new item Web > Global Application Class into the project.
 
WCF3.jpg 
 
Replace the Appilcation_Start event as follows:
  1. protected void Application_Start(object sender, EventArgs e)  
  2. {  
  3.     System.Web.ApplicationServices.AuthenticationService.Authenticating +=    
  4.         new EventHandler<System.Web.ApplicationServices.AuthenticatingEventArgs>(  
  5.         AuthenticationService_Authenticating);  
  6. }  
Add the following event handler:
  1. void AuthenticationService_Authenticating(object sender, System.Web.ApplicationServices.AuthenticatingEventArgs e)         
  2. {         
  3.     e.Authenticated = new UserValidator().IsUserValid(e.UserName, e.Password);       
  4.     e.AuthenticationIsComplete = true;       
  5. }  
The above method extracts the User Name and Password from the Custom Credential object of the Authentication Event Argument. Then it validates the User Name and Password with our UserValidator class.
 
The property Authenticated represents true / false if a user is valid or not respectively.
 
Step 5: Return a Cookie if valid user.
 
Now we need to send back a Cookie if the user is valid. For this add the following code in the above method:
  1. if (e.Authenticated)  
  2. {  
  3.     // Create Cookie  
  4.     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);  
  5.     cookie.Value = e.UserName;  
  6.     // Attach Cookie to Operation Context header  
  7.     HttpResponseMessageProperty response = new HttpResponseMessageProperty();  
  8.     response.Headers[HttpResponseHeader.SetCookie] = cookie.Name + "=" +cookie.Value;  
  9.     OperationContext.Current.OutgoingMessageProperties  
  10.          [HttpResponseMessageProperty.Name] = response;  
  11. }  
The above code performs the following:
  1. Create a cookie with default name (.ASPXAUTH)
  2. Set value to the User Name
  3. Add the cookie to the WCF Operation Context message property
Step 6: Modify the service configuration.
 
Now we need to modify the web.config file to include the following:
  1. Enable Authentication Service
  2. Enable ASP.NET Compatibility
Replace the contents of web.config with the following:
  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   <system.web>  
  4.     <compilation debug="true" targetFramework="4.0" />  
  5.   </system.web>  
  6.   <system.web.extensions>  
  7.     <scripting>  
  8.       <webServices>  
  9.         <authenticationService enabled="true"/>  
  10.       </webServices>  
  11.     </scripting>  
  12.   </system.web.extensions>  
  13.   <system.serviceModel>  
  14.     <behaviors>  
  15.       <serviceBehaviors>  
  16.         <behavior>  
  17.           <serviceMetadata httpGetEnabled="true"/>  
  18.           <serviceDebug includeExceptionDetailInFaults="true"/>  
  19.         </behavior>  
  20.       </serviceBehaviors>  
  21.     </behaviors>  
  22.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />  
  23.   </system.serviceModel>  
  24.   <system.webServer>  
  25.     <modules runAllManagedModulesForAllRequests="true"/>  
  26.   </system.webServer>  
  27. </configuration>  
Step 7: Try accessing the Authentication Service in the Browser.
 
Now build the project and try accessing the AuthenticationService.svc in a browser. If you are able to see the following page then you are on the right track. (Otherwise, please check the steps above for any corrections / use the attached source code.)
 
WCF4.jpg 
 
Step 8, 9, 10: Create a UtilityService.svc with one method named GetData(int).
 
Add a new WCF service named UtilityService.svc into our service application. Delete the existing methods inside the resulting classes and interfaces.
 
Add the following contents to the interface and class respectively.
  1. // IUtilityService.cs  
  2. [ServiceContract]  
  3. public interface IUtilityService  
  4. {  
  5.     [OperationContract]  
  6.     string GetData(int i);  
  7. }  
  8. // UtilityService.svc  
  9. using System.ServiceModel;  
  10. using System.Security.Permissions;  
  11. using System.ServiceModel.Activation;  
  12.   
  13. namespace EntArch_WcfService  
  14. {  
  15.     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  16.     public class UtilityService : IUtilityService  
  17.     {  
  18.         [PrincipalPermission(SecurityAction.Demand, Name = "tom")]  
  19.         public string GetData(int i)  
  20.         {  
  21.             string result = "You Entered: " + i.ToString();  
  22.   
  23.             return result;  
  24.         }  
  25.     }  
  26. }  
The [PrinicalPermission] ensures that only user with name tom is authorized to access the method GetDat(). In the real world applications we will be using the Role property to authorize a group of users.
 
The [AspNetCompatibilityRequirements] ensures that the service can be run in ASP.NET compatibility mode as we are using this mode for our Authentication infrastructure needs.
 
Authorization can be applied in 2 ways:
  • Imperative: Example: if (Roles.IsUserInRole())
  • Declarative: PrincipalPermission
Step 11: Set the Utility Service constructor to set the CurrentPrincipal from the cookie.
 
The WCF Authentication Service had sent a cookie to the user. This cookie will be returned back to the Utility Service (and any new services in the future) by the client. We need to retrieve the cookie and extract the user name out of it. This user name has to be set to the current thread principal. In real projects, you need to set the Roles as well.
 
The following are the activities involved in this step:
  1. Retrieve Cookie from Operation Context Income Message Properties
  2. Extract the User Name from the Cookie
  3. Create a class CustomIdentity implementing IIdentity
  4. Set the Thread Current Principal to the CustomIdentity instance
Modify the constructor of UtilityService as following:
  1. public UtilityService()  
  2. {  
  3.     // Extract Cookie (name=value) from messageproperty  
  4.     var messageProperty = (HttpRequestMessageProperty)  
  5.         OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];  
  6.     string cookie = messageProperty.Headers.Get("Set-Cookie");  
  7.     string[] nameValue = cookie.Split('='',');  
  8.     string userName = string.Empty;  
  9.   
  10.     // Set User Name from cookie  
  11.     if (nameValue.Length >= 2)  
  12.         userName = nameValue[1];  
  13.   
  14.     // Set Thread Principal to User Name  
  15.     CustomIdentity customIdentity = new CustomIdentity();  
  16.     GenericPrincipal threadCurrentPrincipal = new GenericPrincipal(customIdentity, new string[] { });  
  17.     customIdentity.IsAuthenticated = true;  
  18.     customIdentity.Name = userName;  
  19.     System.Threading.Thread.CurrentPrincipal = threadCurrentPrincipal;  
  20. }  
Following is the class definition for CustomIdentity. (You need to place it inside the service project.)
  1. class CustomIdentity : IIdentity  
  2. {  
  3.     public string AuthenticationType  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.   
  9.     public bool IsAuthenticated  
  10.     {  
  11.         get;  
  12.         set;  
  13.     }  
  14.   
  15.     public string Name  
  16.     {  
  17.         get;  
  18.         set;  
  19.     }  
  20. }  
Step 12: Create the client application and add references to both services.
 
Now we are ready to create the client application to consume both the services. Add a new Windows Forms Application to our existing solution and name it as ClientApplication. Make sure you made the Solution Properties > Start Up Projects to start both our Server and Client Applications as shown below.
 
WCF5.jpg 
 
Now Add Service References to the following services:
  1. AuthenticationService.svc
  2. UtilityService.svc
WCF6.jpg 
 
Step 13: Create an Authentication Service instance and invoke the Login() method.
 
Now we are ready to test our Authentication Service. Create a button on the Main Form and name it as Authenticate. On the button click create an instance of the client and invoke the Login() method with the right credentials. You should get a result of true.
  1. private void AuthenticateButton_Click(object sender, EventArgs e)  
  2. {  
  3.     AuthSvc.AuthenticationServiceClient client =   
  4.          new AuthSvc.AuthenticationServiceClient();  
  5.     bool result = client.Login("tom""chicago12"string.Empty, true);  
  6.   
  7.     MessageBox.Show(result.ToString());  
  8. }  
On running the client application and clicking the button you will receive the following output:
 
WCF7.jpg 
 
Step 14: Receive the cookie and store it.
 
The above code just checks the result of Login(). But we need to actually have the returned cookie in case of successful validation. For this we need to replace the above code with the following.
  1. AuthSvc.AuthenticationServiceClient client = new AuthSvc.AuthenticationServiceClient();  
  2.   
  3. using (new OperationContextScope(client.InnerChannel))  
  4. {  
  5.     bool result = client.Login("tom""chicago12"string.Empty);  
  6.     var responseMessageProperty = (HttpResponseMessageProperty) OperationContext.Current.IncomingMessageProperties  
  7.     [HttpResponseMessageProperty.Name];  
  8.   
  9.     if (result)  
  10.     {  
  11.         string cookie = responseMessageProperty.Headers.Get("Set-Cookie");  
  12.         MessageBox.Show(result.ToString() + Environment.NewLine + cookie);  
  13.     }  
  14. }  
The code creates a new OperationContextScope and invokes the Login() method. After invocation the cookie is extracted from the response header.
 
On running the client application again and clicking the button you should be getting the following output.
 
WCF8.jpg 
 
The output displays the result as well as the cookie information. You can see that the cookie name is .ASPXAUTH and the value is tom.
 
Step 15: Create UtilityService instance and invoke GetData() by attaching the stored cookie.
 
Inside the client application we can add a reference to the second service (UtilityService.svc).

Now add a new button with text as Invoke Utility. On the button click handler, add the following code:
  1. private void InvokeUtility_Click(object sender, EventArgs e)  
  2. {  
  3.     UtilSvc.UtilityServiceClient utilClient = new UtilSvc.UtilityServiceClient();  
  4.     string result = utilClient.GetData(10);  
  5.     MessageBox.Show(result);  
  6. }  
On executing the application and clicking the button you will receive the following error:
 
"Request for principal permission failed."
 
WCF10.jpg 
 
The reason for the error is that the current thread user name is not tom. This error can be solved by doing the next step.
 
Step 16: Attach the Cookie to UtilityService client.
 
In order to solve the above error, we need to attach the cookie from the Authentication Service to the current Operation Context. We need to extract the variable cookie out of the Authentication Method so that it can be used in the Utility Invocation method.
 
WCF11.jpg 
 
Now replace the contents of InvokeUtility_Click with the following:
  1. private void InvokeUtility_Click(object sender, EventArgs e)  
  2. {  
  3.     if (string.IsNullOrEmpty(cookie))  
  4.     {  
  5.         MessageBox.Show("Please click Authenticate first.");  
  6.         return;  
  7.     }  
  8.   
  9.     UtilSvc.UtilityServiceClient utilClient = new UtilSvc.UtilityServiceClient();  
  10.   
  11.     using (new OperationContextScope(utilClient.InnerChannel))  
  12.     {  
  13.   
  14.         HttpRequestMessageProperty request = new HttpRequestMessageProperty();  
  15.         request.Headers[HttpResponseHeader.SetCookie] = cookie;  
  16.         OperationContext.Current.OutgoingMessageProperties  
  17.                  [HttpRequestMessageProperty.Name] = request;  
  18.   
  19.         string result = utilClient.GetData(10);  
  20.         MessageBox.Show(result);  
  21.     }  
  22. }  
The method now performs the following activities:
  1. Ensure the cookie field is has a value (Valid Authentication Service Call needed)
  2. Create a Http Request Message Property set to cookie field
  3. Attaches the Message Property instance to the Operation Context
Step 17: Test the application and ensure proper functioning.
 
Now we are ready with the Authentication and Authorization infrastructure. Please run the application and test the features in 2 steps:
 
WCF12.jpg 
  1. Click the Authenticate button and wait for the response
  2. Click the Invoke Utility button
You will be getting the following Message Box on successful Authorization.
 
WCF13.jpg 
 
If you can see the above result.. Great!! You are done with Authentication and Authorization.
 
Step 18: Move the cookie attaching code to Interceptors in the Client Application.
 
Now we need to implement Interceptors in the client side.
 
Why do we need Interceptors?
 
This is because the above code of attaching a cookie to the Operation Context seems to be a tedious job every time we need to do a service call. We can move these tasks to the background using WCF Interceptors.
 
MSDN: WCF Data Services enables an application to intercept request messages so that you can add custom logic to an operation. You can use this custom logic to validate data in incoming messages. You can also use it to further restrict the scope of a query request, such as to insert a custom authorization policy on a per request basis.
 
The following are the activities involved in this step.
  1. Add Interceptor Behavior inside Client web.config
  2. Create the Interceptor Behavior class
  3. Create the Message Inspector class
  4. Move the code from Form to Message Inspector class
To start with that, add the following code into the Client Application app.config file. Make sure you add them just before the </system.serviceModel> tag.
  1. <!-- Interceptors-->  
  2. <behaviors>  
  3.   <endpointBehaviors>  
  4.     <behavior name="InterceptorBehaviour">  
  5.       <interceptorBehaviorExtension />  
  6.     </behavior>  
  7.   </endpointBehaviors>  
  8. </behaviors>  
  9. <extensions>  
  10.   <behaviorExtensions>  
  11.     <add name="interceptorBehaviorExtension" type="ClientApplication.InterceptorBehaviorExtension,   
  12.           ClientApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
  13.   </behaviorExtensions>  
  14. </extensions>  
Change the Behavior Configuration element of the Utility Service section as shown below.
 
WCF14.jpg 
 
Now we need to create the Behavior Extension and Interceptor classes inside the Client Application.
  1. // Behavior Extension Class - Attaches Cookie Inspector to the client behavior  
  2.   
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.ServiceModel.Description;  
  8. using System.ServiceModel.Configuration;  
  9.   
  10. namespace ClientApplication  
  11. {  
  12.     public class InterceptorBehaviorExtension : BehaviorExtensionElement, IEndpointBehavior  
  13.     {  
  14.         public override System.Type BehaviorType  
  15.         {  
  16.             get { return typeof(InterceptorBehaviorExtension); }  
  17.         }  
  18.   
  19.         protected override object CreateBehavior()  
  20.         {  
  21.             return new InterceptorBehaviorExtension();  
  22.         }  
  23.   
  24.         public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)  
  25.         {  
  26.               
  27.         }  
  28.   
  29.         public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)  
  30.         {  
  31.             clientRuntime.MessageInspectors.Add(new CookieMessageInspector());  
  32.         }  
  33.   
  34.         public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)  
  35.         {  
  36.   
  37.         }  
  38.   
  39.         public void Validate(ServiceEndpoint endpoint)  
  40.         {  
  41.   
  42.         }  
  43.     }  
  44. }
  1. // Cookie Inspector Class  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.ServiceModel.Dispatcher;  
  7. using System.ServiceModel.Channels;  
  8. using System.Net;  
  9. using System.Windows.Forms;  
  10.   
  11. namespace ClientApplication  
  12. {  
  13.     public class CookieMessageInspector : IClientMessageInspector  
  14.     {  
  15.         private string cookie;  
  16.   
  17.         public CookieMessageInspector()  
  18.         {  
  19.   
  20.         }  
  21.   
  22.         public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply,  
  23.             object correlationState)   
  24.         {   
  25.         }  
  26.   
  27.         public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  
  28.             System.ServiceModel.IClientChannel channel)  
  29.         {  
  30.             if (string.IsNullOrEmpty(Globals.Cookie))  
  31.             {  
  32.                 MessageBox.Show("No Cookie Information found! Please Authenticate.");  
  33.                 return null;  
  34.             }  
  35.   
  36.             HttpRequestMessageProperty requestMessageProperty = new HttpRequestMessageProperty();  
  37.             requestMessageProperty.Headers[HttpResponseHeader.SetCookie] = Globals.Cookie;  
  38.             request.Properties[HttpRequestMessageProperty.Name] = requestMessageProperty;  
  39.   
  40.             return null;  
  41.         }  
  42.     }  
  43. }  
ApplyClientBehavior: This method enables us to attach client-side behaviors to the WCF calls. We are attaching a Cookie Inspector (CookieMessageInspector) in this method.
 
CookieMessageInspector: This class takes care of attaching the cookie to outgoing message properties (through BeforeSendRequest method). The cookie is saved in the Globals.Cookie property after the Authentication Service is called.
 
Step 19: Move the identity setting code to Interceptors in the Service Application.
 
You can remember that our UtilityService.svc has a substantial amount of code in the constructor doing the following:
  • Extracting Cookie from Current Operation Context
  • Getting the User Name from the Cookie
  • Setting User Name to the Current Thread
This code for one utility seems to be fine. But in the case of dozens of Utility services the same code needs to be duplicated. We can solve this by using background interceptors in the service side. For this we can use the same BehaviorExtension and Inspector classes with slight modifications.
 
Place the following files in the WCF Service Application.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel.Description;  
  6. using System.ServiceModel.Configuration;  
  7. using System.ServiceModel.Dispatcher;  
  8.   
  9. namespace EntArch_WcfService  
  10. {  
  11.     public class InterceptorBehaviorExtension : BehaviorExtensionElement, IServiceBehavior  
  12.     {  
  13.         public override Type BehaviorType  
  14.         {  
  15.             get { return typeof(InterceptorBehaviorExtension); }  
  16.         }  
  17.   
  18.         protected override object CreateBehavior()  
  19.         {  
  20.             return new InterceptorBehaviorExtension();  
  21.         }  
  22.    
  23.         public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase,   
  24. System.Collections.ObjectModel.Collection  
  25. <ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)  
  26.         {  
  27.   
  28.         }  
  29.   
  30.         public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)  
  31.         {  
  32.             foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)  
  33.             {  
  34.                 foreach (var endpoint in dispatcher.Endpoints)  
  35.                 {  
  36.                     endpoint.DispatchRuntime.MessageInspectors.Add(new IdentityMessageInspector());  
  37.                 }  
  38.             }  
  39.         }  
  40.    
  41.         public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)  
  42.         {  
  43.   
  44.         }  
  45.     }  
  46. }  
  1. // IdentityMessageInspector.cs  
  2.   
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.ServiceModel.Dispatcher;  
  8. using System.ServiceModel.Channels;  
  9. using System.Net;  
  10. using System.IO;  
  11. using System.ServiceModel;  
  12. using System.Security.Principal;  
  13.   
  14. namespace EntArch_WcfService  
  15. {  
  16.     public class IdentityMessageInspector : IDispatchMessageInspector  
  17.     {  
  18.         public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.  
  19. InstanceContext instanceContext)  
  20.         {  
  21.             // Extract Cookie (name=value) from messageproperty  
  22.             var messageProperty = (HttpRequestMessageProperty)  
  23.                 OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];  
  24.             string cookie = messageProperty.Headers.Get("Set-Cookie");  
  25.             string[] nameValue = cookie.Split('='',');  
  26.             string userName = string.Empty;  
  27.   
  28.             // Set User Name from cookie  
  29.             if (nameValue.Length >= 2)  
  30.                 userName = nameValue[1];  
  31.   
  32.             // Set Thread Principal to User Name  
  33.             CustomIdentity customIdentity = new CustomIdentity();  
  34.             GenericPrincipal threadCurrentPrincipal = new GenericPrincipal(customIdentity, new string[] { });  
  35.             customIdentity.IsAuthenticated = true;  
  36.             customIdentity.Name = userName;  
  37.             System.Threading.Thread.CurrentPrincipal = threadCurrentPrincipal;  
  38.   
  39.             return null;  
  40.         }  
  41.   
  42.         public void BeforeSendReply(ref Message reply, object correlationState)  
  43.         {  
  44.               
  45.         }  
  46.     }  
  47. }  
Now remove the code from the UtilityService constructor. The new constructor will look empty.
  1. public UtilityService()  
  2. {  
  3.   
  4. }  
Now add the following code to the web.config file of the service just under <system.serviceModel>
  1. <services>  
  2.     <service name="EntArch_WcfService.UtilityService" behaviorConfiguration="InterceptorBehavior"/>  
  3.   </services>  
  4.   <behaviors>  
  5.     <serviceBehaviors>  
  6.       <behavior>  
  7.         <serviceMetadata httpGetEnabled="true"/>  
  8.         <serviceDebug includeExceptionDetailInFaults="true"/>  
  9.       </behavior>  
  10.       <behavior name="InterceptorBehavior">  
  11.         <interceptorBehaviorExtension />  
  12.       </behavior>  
  13.     </serviceBehaviors>  
  14.   </behaviors>  
  15.   <extensions>  
  16.     <behaviorExtensions>  
  17.       <add name="interceptorBehaviorExtension" type="EntArch_WcfService.InterceptorBehaviorExtension, EntArch_WcfService, Version=1.0.0.0,   
  18. lture=neutral, PublicKeyToken=null" />  
  19.     </behaviorExtensions>  
  20.   </extensions>  
Please make sure that the namespaces are correct and build the project.
 
Step 20: Modify the service-side code to include Role instead of Name.
 
The current Authorization code is hardcoded with the user name Tom. But this is not feasible in the real world. We need to change the user name authorization to role-based authorization.
 
Here each validated user has certain roles associated with them. This role information will be fetched from the database during the Authentication process and passed along with the cookie to the user.
 
Example:
 
User
Roles
tom
Read
pike
Read, Write
 
The roles are kept as strings and we can separate methods based on the roles as given below:
  1. [PrincipalPermission(SecurityAction.Demand, Role = "Read")]  
  2. public string GetData(int i)  
  3. {}  
  4. [PrincipalPermission(SecurityAction.Demand, Role = "Write")]  
  5. public string SetData(int i)  
  6. {}  
To accomplish the above we need to modify the following.
  1. Modify UserValidator.IsUserVaild to return roles from database
  2. Modify the AuthenticationService_Authenticating.Authentication method to include roles
  3. Concatenate the user name and roles in the cookie value as semicolon (;) separated
  4. Modify the Identity Inspector to retrieve roles from the cookie value
The modifications are given below:
  1. // UtilityService  
  2.   
  3. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
  4. public class UtilityService : IUtilityService  
  5. {  
  6.     public UtilityService()  
  7.     {  
  8.   
  9.     }  
  10.   
  11.     [PrincipalPermission(SecurityAction.Demand, Role = "Read")]  
  12.     public string GetData(int i)  
  13.     {  
  14.         string result = "You Entered: " + i.ToString();  
  15.   
  16.         return result;  
  17.     }  
  18. }  
  19.   
  20. // User Validator  
  21. public class UserValidator  
  22. {  
  23.     public bool IsUserValid(string userName, string password, out IList<string> roles  
  24.      )  
  25.     {  
  26.         roles = new List<string>();  
  27.   
  28.         bool result = (userName == "tom") && (password == "chicago12");  
  29.   
  30.         if (result) // If valid user return the Roles of user  
  31.             roles.Add("Read");  
  32.   
  33.         return result;  
  34.     }  
  35. }  
  36.   
  37. private string Concatenate(string userName, IList<string> roles)  
  38. {  
  39.     string result = userName + ";";  
  40.   
  41.     foreach (string role in roles)  
  42.         result += role + ";";  
  43.   
  44.     return result;  
  45. }  
Please note that the Read role is hardcoded in the above code:
  1.       // Identity Message Inspector  
  2.   
  3.        public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext   
  4. instanceContext)  
  5.         {  
  6.             // Extract Cookie (name=value) from messageproperty  
  7.             var messageProperty = (HttpRequestMessageProperty)  
  8.                 OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];  
  9.             string cookie = messageProperty.Headers.Get("Set-Cookie");  
  10.             string[] nameValue = cookie.Split('='',');  
  11.             string value  
  12.                 = string.Empty;  
  13.   
  14.             // Set User Name from cookie  
  15.             if (nameValue.Length >= 2)  
  16.                 value = nameValue[1];  
  17.   
  18.             string userName = GetUserName(value);  
  19.             string[] roles = GetRoles(value);  
  20.   
  21.             // Set Thread Principal to User Name  
  22.             CustomIdentity customIdentity = new CustomIdentity();  
  23.             GenericPrincipal threadCurrentPrincipal = new GenericPrincipal(customIdentity, roles);  
  24.             customIdentity.IsAuthenticated = true;  
  25.             customIdentity.Name = value;  
  26.             System.Threading.Thread.CurrentPrincipal = threadCurrentPrincipal;  
  27.   
  28.             return null;  
  29.         }  
  30.   
  31.         private string[] GetRoles(string value)  
  32.         {  
  33.             if (!string.IsNullOrEmpty(value))  
  34.             {  
  35.                 List<string> roles = new List<string>();  
  36.   
  37.                 int ix = 0;  
  38.                 foreach (string item in value.Split(';'))  
  39.                 {  
  40.                     if (ix > 0)  
  41.                         if (item.Trim().Length > 0)  
  42.                             roles.Add(item);  
  43.   
  44.                     ix++;  
  45.                 }  
  46.   
  47.                 return roles.ToArray<string>();  
  48.             }  
  49.   
  50.             return new string[0];  
  51.         }  
  52.   
  53.         private string GetUserName(string value)  
  54.         {  
  55.             if (!string.IsNullOrEmpty(value))  
  56.             {  
  57.                 foreach (string item in value.Split(';'))  
  58.                     return item;  
  59.             }  
  60.    
  61.             return string.Empty;  
  62.         }  
Once the above codes has been modified and ready, you can run the application. Try changing the role in the PrincipalPermission atttirube to Write and you will get an error on accessing the GetData() method.
 
Step 21: Create Cookie Encryption.
 
As of now our cookie contains information that is easily readable by HTTP Examining Utilities like Fiddler. This makes the cookie information prone to security threats.
 
WCF15.jpg 
 
In this step we are going to add encryption to the cookie value. The above image displays the value which we are going to encrypt (username;Role)
 
FormsAuthenticationTicket: The System.Web.Security namespace provides a convenient class for us. We can store the user name and roles information inside this class instance. The ticket class also provides expiry and encryption facilities.
 
The following code creates the ticket:
  1. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(  
  2.     1,   
  3.     e.UserName,   
  4.     DateTime.Now,   
  5.     DateTime.Now.AddHours(24),   
  6.     true,   
  7.     roles,  
  8.     FormsAuthentication.FormsCookiePath);  
The following code encrypts the ticket:
  1. string encryptedValue = FormsAuthentication.Encrypt(ticket);  
Now we can pass the ticket as name value pair through the message properties:
  1. HttpResponseMessageProperty response = new HttpResponseMessageProperty();  
  2. response.Headers[HttpResponseHeader.SetCookie] = FormsAuthentication.FormsCookieName + "=" + encryptedValue;  
  3. OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] = response;  
You need to specify the Cookie Name, Machine Key Properties inside the web.config as shown below:
  1. <configuration>  
  2.     <system.web>  
  3.         <compilation debug="true" targetFramework="4.0" />  
  4.         <authentication mode="Forms">  
  5.             <forms slidingExpiration="true"  
  6.               name="AuthCookie"  
  7.               protection="All"  
  8.               timeout="20"/>  
  9.         </authentication>  
  10.         <machineKey  
  11.           decryption="AES"  
  12.           validation="SHA1"  
  13.           decryptionKey="1523F567EE75F7FB5AC0AC4D79E1D9F25430E3E2F1BCDD3370BCFC4EFC97A541"  
  14.           validationKey="33CBA563F26041EE5B5FE9581076C40618DCC1218F5F447634EDE8624508A129"  
  15.          />  
  16.     </system.web>  
In the Identity Inspector we need to change the message property parsing code to reconstruct the Ticket.
 
// The updated code can be found in the attachment
 
On running the client application we can see that the message information is now encrypted.
 
WCF16.jpg 
 
Step 22: Retest the Application.
 
Now perform the following activities:
  1. Set the property of the client app.config to Copy Always.
  2. Execute the Application
  3. Click on the Authenticate button
  4. Click on the Utility Invoke button
Upon performing the button clicks as specified in Step 17, the same results should be achieved.
 
WCF17.jpg 
 
We can see the result as shown below:
 
WCF18.jpg 
 
This concludes our article on WCF Authentication using Cookies. I hope you enjoyed the learning curves and solutions.
 
References
 
 
Summary
 
In this article we have seen how to expose a WCF Service Application along with Authentication Service and Authorization according to Enterprise Architecting standards.
 
The following are the activities involved:
  1. The client authenticates using the AuthenticationService.svc and receives a cookie.
  2. The authenticated cookie is used in further communications.
  3. The Authorization part is played by the PrincipalPermission attribute.
  4. The WCF Interceptors do a good job by doing cookie attaching in the background.
You can note that the client needs to authenticate only once. Later the cookie received is used to access other services. Based on the real-time requirements we need to enable Ticket Expiry as well.
 
The attached source contains the projects we have explained. Please let me know of any clarifications or query you have.
 
In the next article, we can see use of a Silverlight application to use the same service.


Similar Articles