Donate

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:
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:
[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!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.