Tuesday, October 19, 2010

Authorization and Authentication using WCF Security - Silverlight

  In my previous articles Silverlight 4.0 - Calling Secured WCF 4.0 Service hosted with SSL and Self-Signed Certificate, we saw how to consume WCF SSL enabled service in Silverlight 4.0 client and in the article Silverlight 4.0 - Secure Communication to WCF service using Custom User Name and Password Validator, we saw how to authenticate a user using by using custom user name and password. As an extension to these articles, we will now  explore how to authenticate a Silverlight user against WCF service to perform business operations like Read All and Insert etc.
To perform these operations, I have used the Windows Server 2008 R2 with Active Directory configurations and added two users in it as shown below:
·         Domain Name: Mithilla.
·         User 1: Leena.
·         User 2: Tejas.
In .NET framework we have been provided with ‘System.Security’ namespace using which ‘PrincipalPermission’ can be set on various operations exposed by WCF services. This object provides ‘Name’ and ‘Role’ properties using which operations can be configured against user name of its role, to execute a specific operation in the WCF service.      
In this article, we will design a WCF service which is hosted on IIS with SSL and Self signed certificate. The complete process of configuring and comsuming SSL and self signed certificates is already explained here Silverlight 4.0 - Calling Secured WCF 4.0 Service hosted with SSL and Self-Signed Certificate
Creating a WCF service with Authorization attributes
Step 1: Open VS2010 and create a blank solution and name it as ‘WCF_Authorization_Authentication’. In this solution, add a WCF service project and name it as ‘WCF_Authorization_Service’. Rename ‘IService1.cs’ to ‘IService’, rename ‘Service1.svc’ to ‘Service.svc’.
Step 2: Right click ‘Service.svc’ and select ‘View Markup’ and change the ‘Service’ attribute of @ServiceHost as below:
<%@ ServiceHost Language="C#" Debug="true" Service="WCF_Authorization_Service.Service" CodeBehind="Service.svc.cs" %>
Step 3: Open ‘IService.cs’ and write the following code for ServiceContract and OperationContract etc.
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace WCF_Authorization_Service
{
   [ServiceContract]
   public interface IService
   {
       [OperationContract]
       List<Employee> GetAllEmployees();
       [OperationContract]
       [FaultContract(typeof(CustomFaultMessage))]
       void CreateEmployee(Employee objEmp);
   }
   [DataContract]
  public class Employee
   {
       [DataMember]
       public int EmpNo { get; set; }
Read more: net curry .com