Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC redirect to an access denied page using a custom role provider

I'm creating a custom role provider and I set a Authorize attribute specifying a role in my controller and it's working just fine, like this:

[Authorize(Roles="SuperAdmin")] public class SuperAdminController : Controller ... 

But when an user doens't have access to this controller, he's redirected to login page. How can I redirect him to a "AcessDenied.aspx" page?

like image 829
André Miranda Avatar asked Aug 14 '09 19:08

André Miranda


2 Answers

[AccessDeniedAuthorize(Roles="SuperAdmin")] public class SuperAdminController : Controller 

AccessDeniedAuthorizeAttribute.cs:

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute {     public override void OnAuthorization(AuthorizationContext filterContext)     {         base.OnAuthorization(filterContext);          if(filterContext.Result is HttpUnauthorizedResult)         {             filterContext.Result = new RedirectResult("~/AcessDenied.aspx");         }     } } 
like image 106
eu-ge-ne Avatar answered Sep 19 '22 21:09

eu-ge-ne


Here's my solution, based on eu-ge-ne's answer. Mine correctly redirects the user to the Login page if they are not logged in, but to an Access Denied page if they are logged in but are unauthorized to view that page.

[AccessDeniedAuthorize(Roles="SuperAdmin")] public class SuperAdminController : Controller 

AccessDeniedAuthorizeAttribute.cs:

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute {     public override void OnAuthorization(AuthorizationContext filterContext)     {         base.OnAuthorization(filterContext);         if (!filterContext.HttpContext.User.Identity.IsAuthenticated)         {             filterContext.Result = new RedirectResult("~/Account/Logon");             return;         }          if (filterContext.Result is HttpUnauthorizedResult)         {             filterContext.Result = new RedirectResult("~/Account/Denied");         }     } } 

AccountController.cs:

public ActionResult Denied() {     return View(); } 

Views/Account/Denied.cshtml: (Razor syntax)

@{     ViewBag.Title = "Access Denied"; }  <h2>@ViewBag.Title</h2>  Sorry, but you don't have access to that page. 
like image 41
Matt Frear Avatar answered Sep 17 '22 21:09

Matt Frear