Showing posts with label Custom AuthorizeAttribute in mvc4. Show all posts
Showing posts with label Custom AuthorizeAttribute in mvc4. Show all posts

Tuesday, May 28, 2013

Custom AuthorizeAttribute example in mvc4 razor

Here i am sharing an example of creating a custom AuthorizeAttribute in mvc4 application, and its implementation.

Step 1 :
Create a class

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeAdminAuthorizeAttribute : AuthorizeAttribute
  {
protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                isAuthorized = false;
            }
         
            if (httpContext.User.Identity.Name == null)
                isAuthorized = false;
            else
                isAuthorized = true;

            return isAuthorized;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
             
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(filterContext);
                filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "AdminAccount", action = "Index" }));
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new { controller = "JewelAdmin", action = "Index" }));
            }
        }
   }

Step 2:
Now we see how to call the authorize attribute in action

 [AuthorizeAdminAuthorize]
        public ActionResult AddProduct()
        {
 return View();
        }

So, now in whichever action you want authorization to be checked , just put [AuthorizeAdminAuthorize] attribute on top of that ActionResult