Authentication and Authorization Using IPrincipal Interface

Authentication is the process of the system identifying an individual based on the information provided by him. That is generally the user id and word. Authentication is essential for effective security. Authentication is different from authorization. Whereas the former means only identifying the user, the latter means denying or granting some access to someone.

IPrincipal defines the basic functionality of a principal object. The security context of the user for whom the code is running is represented by the IPrincipal object, along with that user's identity (IIdentity) and any roles to which they belong.

In this example we will use the IPrinicipal interface instead of IIdentity and then override PostAuthenticateRequest in global.asax.cs for reading the value from a cookie.

1. Creating the interface

In the following sample the interface MyIPrincipal is inherited from the IPrincipal inheritance.

  1. interface MyIPrincipal: IPrincipal  
  2. {  
  3.    string Id { getset; }  
  4.    string UserName { getset; }  
  5. }  

Next we shall create a custom interface.

2. Creating a custom interface

We will be inheriting this custom interface from the interface we just inherited from the IPrincipal interface. In the following sample we have created a custom interface MyCustomPrincipal and added all the custom information we need.

  1. public class MyCustomPrincipal : MyIPrincipal  
  2. {  
  3.    public IIdentity Identity { getprivate set; }  
  4.    public bool IsInRole(string role) { return false; }  
  5.    public MyCustomPrincipal(string email)  
  6.    {  
  7.       this.Identity = new GenericIdentity(email);   
  8.    }  
  9.    public string Id { getset; }  
  10.    public string UserName { getset; }  
  11.    public int IsAdmin { getset; }  
  12. }  

Next, we need to create a class that will serialize all the properties and custom information of MyCustomPrincipal into the userdata field of the FormsAuthenticationTicket object.

3. Creating a serialize model

In the following sample we create a serializer for serializing the object of type MyCustomPrincipal into the userdata field of the FormsAuthenticationTicket object. 

  1. public class CustomPrincipalSerializer  
  2. {  
  3.    public string Id { getset; }  
  4.    public string UserName { getset; }  
  5.    public int IsAdmin { getset; }  
  6. }  

Now we need to create a cookie to save all the custom information. So, for this we create a method in the login page.

4. Saving information in the cookie

In the following code we create a method, SaveSession. In this method we serialize the user details and save that in the FormsAuthenticationTicket object's userData field. 

  1. CustomPrincipalSerializer objSerializer = new CustomPrincipalSerializer();  
  2. objSerializer.Id = user.UserHashCode;  
  3. objSerializer.UserName = user.UserName;  
  4. objSerializer.IsAdmin = Convert.ToInt16(user.IsAdmin);  
  5. JavaScriptSerializer serializer = new JavaScriptSerializer();  
  6. string userData = serializer.Serialize(objSerializer);  
  7. FormsAuthenticationTicket formAuthTicket = null;  
  8. formAuthTicket = new FormsAuthenticationTicket(1,user.EmailId,DateTime.Now,DateTime.Now.AddMinutes(15),false,userData);  
  9. string encformAuthTicket = FormsAuthentication.Encrypt(formAuthTicket);  
  10. HttpCookie formAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encformAuthTicket);  
  11. System.Web.HttpContext.Current.Response.Cookies.Add(formAuthCookie);  

The FormsAuthenticationTicket object is then encrypted and saved in the HttpContext’s cookies.

After the cookie is added we call another method SaveSessionData to save the encrypted cookie value in the database.

5.Reading information from the cookie

We ought to override a PostAuthenticateRequest method in the global.asax.cs. Here we read the cookie and replace HttpContext’s user object with it. 

  1. HttpCookie formAuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName];  
  2. if (formAuthCookie != null)  
  3. {  
  4.    //Decrypt the cookie value.  
  5.    FormsAuthenticationTicket formAuthTicket = FormsAuthentication.Decrypt(formAuthCookie.Value);  
  6.    JavaScriptSerializer objSerializer = new JavaScriptSerializer();  
  7.    //Deserialize the cookie value  
  8.    CustomPrincipalSerializer serializeModel = objSerializer.Deserialize<CustomPrincipalSerializer>(formAuthTicket.UserData);  
  9.    MyCustomPrincipal newUser = new MyCustomPrincipal(formAuthTicket.Name);   
  10.    newUser.Id = serializeModel.Id;  
  11.    newUser.UserName = serializeModel.UserName;  
  12.    newUser.IsAdmin = serializeModel.IsAdmin;  
  13.    //Save details in the httpcontext  
  14.    HttpContext.Current.User = newUser;  
  15. }  
6.Accessing the information

In the PostAuthenticateRequest method the cookie value is read, decrypted, de-serialized and saved in HttpContext’s user instance for further access.

In this example I have used webform, so in the master page we can read the value of the current user from HttpContext and use it throughout the application.

  1. public MyCustomPrincipal CurrentUser  
  2. {  
  3.    get  
  4.    {  
  5.     if (HttpContext.Current.User != null)  
  6.     {  
  7.        return HttpContext.Current.User as MyCustomPrincipal;  
  8.     }  
  9.     else  
  10.     {  
  11.        return null;  
  12.     }  
  13.    }  
  14. }  
Now we can use a HttpContext.User object, CurrentUser to access the values saved in the cookie. In the following example we first check whether the user exists or not, if the user exists we just access the value we require. It is as simple as that.

The following screen shot shows all the cookies set by the page before log in. 

And, here we can see all the cookies set by the page after login. The method used in this example for saving data in the cookie is secured, because the value saved in the cookie is encrypted. 

To remove the cookie from the browser, we need to use the FormAuthentication’s SignOut method. 

The SignOut method, as used in the preceding, removes the form authentication ticket from the browser.

Thank you for reading. I hope it helps you all.