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

No comments:

ETG Consultancy

Web Designing Development Analysis & Promotion
Asp.Net 2.0 SQL WWF WCF SEO Marketing Ajax JQuery NHibernate MVC