MVC custom authorization filter

Step 1: Create new CustomAuthorizeAttribute.cs class and inherit it from AuthorizeAttribute. Now write the following code in that class.

 public class CustomAuthorizeAttribute AuthorizeAttribute
    {
        //For handle single role
        public string Role = string.Empty;

        public override void OnAuthorization(AuthorizationContext actionContext)
        {
            if (!SkipAuthorization(actionContext))
            {
                var sessionId actionContext.HttpContext.Request.Headers.Get("SessionId");
                if (string.IsNullOrEmpty(sessionId))
                {
                    RedirectToLogin(actionContext);
                }

                bool validate = true; //To Do : Validate SessionId from the database.
                if (!validate)
                {
                    RedirectToLogin(actionContext);
                }
            }
        }

        public void RedirectToLogin(AuthorizationContext filterContext)
        {
            filterContext.Result =
                new RedirectToRouteResult(new RouteValueDictionary(
                    new
                    {
                        controller = "Account",
                        action = "Unauthorized",
                        area = "",
                        returnUrl = filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery
                    }));
        }

        //This function checks the AllowAnonymous attribute existance on the controller action method.
        private bool SkipAuthorization(AuthorizationContext filterContext)
        {
            Contract.Assert(filterContext != null);

            return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()
                   || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
        }
    }

Step 2: Now add this CustomAuthorize attribute on the home controller. CustomAuthorize attribute checks the "SessionId" in the request headers and validate the "SessionId" of logged in user. If that "SessionId" is invalid then it redirect the user to "Unauthorized" action of Account controller. 

[CustomAuthorize]
 public class HomeController Controller
    {
        public ActionResult Dashboard()
        {
            return View();
        }
    }

 public class AccountController : Controller
    {
        public ActionResult Unauthorized()
        {
            return View();
        }


    }

Comments

Popular posts from this blog

MVC Implementing Dependency Injection.

MVC handle multiple submit buttons in ASP.NET MVC.