Wednesday, March 19, 2014

Redirect unauthorized access to a custom view instead of redirecting to a login view in ASP.NET MVC 4

One might encounter when implementing the forms authentication framework(WebMatrix)is that when a user access a specific url/controller and he/she is unauthorized, the application always redirect's to the default log-in view. In order to solve this minor issue, one solution is to develop a custom class that inherit's the AuthorizeAttribute class and override the HandleUnauthorizedRequest method as shown below:
Code:
public class AuthorizeUsersAttribute : AuthorizeAttribute
    {
        private string redirectUrl = "";
        
        public string NotifyUrl
        {
            get { return redirectUrl; }
            set { redirectUrl = value; }
        }

        public AuthorizeUsersAttribute()
            : base()
        {
        }

        public AuthorizeUsersAttribute(string redirectUrl)
            : base()
        {
            this.redirectUrl = redirectUrl;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                string authUrl = this.redirectUrl; //passed from attribute NotifyUrl Property

                //if null, get it from config
                if (String.IsNullOrEmpty(authUrl))
                    authUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RolesAuthRedirectUrl"];

                if (!String.IsNullOrEmpty(authUrl))
                    filterContext.HttpContext.Response.Redirect(authUrl);
            }

            //else do normal process
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
Sample usage on a controller:
Code:
[AuthorizeUsers(Roles = "Administrator", NotifyUrl = "/Errors/UnAuthorizedUser")]
public ActionResult Delete(string id = null)
{
    Customer customer = db.Customers.Find(id);
    if (customer == null)
    {
        return RedirectToAction("Errors", "Http404");      
    }
    return View(customer);
}

Based from the code above, only administrator's can access the page. Once an unauthorized activity happens, it will redirect to an UnAuthorizedUser action from Errors controller. The action might as well render a partial view or customized code.

Cheers!

0 comments:

Post a Comment