About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

Web Application Custom Authentication

In order to implement custom authentication, application’s forms cookie need to override with custom user object with implementation of IPrincipal and IIdentity interfaces.
When application request for authenticate user then system fire an event of Application object.  
Implement authentication in Global.asax.cs
Add Application_AuthenticateRequest event into the Global.asax with AuthenticationTicket extension method.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
      Context.AuthenticationTicket();//invoke extension method
}
When user request for login with valid credential, application should authenticate user and set application’s forms cookie with encrypted user information so next time user try to access any resources which required authenticate user, user will be authenticate by Application_AuthenticateRequest using application’s forms cookie.
To set authentication cookie 
Call AuthenticationProcessor.SetAuthenticationTicket(httpContext, user);
 
Create a static class to implement extension methods as below  
using System;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using DemoLib.Shared.Models;
 
namespace Mvc3Demo.Core
{
    public static class AuthenticationProcessor
    {
        public static void SetAuthenticationTicket(this HttpContextBase httpContext, User user)
        {
            var ticket = new UserTicket
                             {
                                 Name = user.UserName,
                                 Role = user.Role.RoleName,
                                 Id = user.Id
                             };
 
            var jsonSerializer = new JavaScriptSerializer();
 
            var userData = jsonSerializer.Serialize(ticket);
 
            var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(1), false, userData);
 
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
 
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
 
            httpContext.Response.Cookies.Add(authCookie);
        }
 
        public static void AuthenticationTicket(this HttpContext httpContext)
        {
            HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
 
            if (authCookie == null || string.IsNullOrEmpty(authCookie.Value))
                return;
 
            try
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                
                var jsonSerializer = new JavaScriptSerializer();
 
                var ticket = jsonSerializer.Deserialize<UserTicket>(authTicket.UserData);
 
                var demoIdentity = new DemoIdentity(ticket.Name)
                                       {
                                           User = ticket,
                                       };
 
                httpContext.User = new DemoPrincipal(demoIdentity);
            }
            catch (Exception ex)
            {
 
            }
        }
 
        public class DemoPrincipal : IPrincipal
        {
            private readonly DemoIdentity _loyaltIdentity;
 
            public DemoPrincipal(DemoIdentity loyaltIdentity)
            {
                _loyaltIdentity = loyaltIdentity;
            }
            public bool IsInRole(string role)
            {
                return role.Contains(_loyaltIdentity.User.Role);
            }
 
            public IIdentity Identity { get { return _loyaltIdentity; } }
 
            public DemoIdentity LoyaltIdentity { get { return _loyaltIdentity; } }
        }
 
        public class DemoIdentity : IIdentity
        {
            public DemoIdentity(string name)
            {
                Name = name;
            }
 
            public string Name { getprivate set; }
            public string AuthenticationType { get { return "Custom"; } }
            public bool IsAuthenticated { get { return true; } }
 
            public UserTicket User { getset; }
 
        }
 
        public class UserTicket
        {
            public int Id { getset; }
            public string Name { getset; }
            public string Token { getset; }
            public string Role { getset; }
        }
    }
}

No comments :