Friday 24 May 2013

Custom ASP.NET MVC Authorize Attribute

AuthorizeAttribute allows you to secure controller actions. The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users. This gives you a high degree of control over who is authorized to view any page on the site.


public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        // Custom property as you can get Page name which is passed from controller
        public string AccessLevel { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;
            else
            {
                //Check Roles
                HttpCookie authCookie =          httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null || authCookie.Value == "")
                {
                }
                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                catch
                {
                }        
                // retrieve roles from UserData
                string[] roles = authTicket.UserData.Split(';');
            }                
            return true;
    }


Here I just override the AuthorizeCore methods of AuthorizeAttribute class. Now, you have to decorate your controller or action with this custom attribute

[CustomAuthorize(AccessLevel = "DemoIndex")]
 public ActionResult DemoIndex()
{
       return View();
}


You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                            { 
                                controller = "Error", 
                                action = "Unauthorised" 
                            })
                    );
    }

No comments:

Post a Comment