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:
Sample usage on a controller:
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!
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); } }
[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); }
Cheers!
Comments
Post a Comment