Question Summary: In ASP.NET MVC, is there a clean way to prevent a specific user or role from accessing an action?
Obviously, the following would allow roles Admin
and Editor
to access the entire controller.
[Authorize(Roles = "Admin, Editor")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
If I only wanted the Admin
role to have access to the About
action, I could do the following:
[Authorize(Roles = "Admin, Editor")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize(Roles = "Admin")] // this will take precedence over the controller's authorization
public ActionResult About()
{
return View();
}
}
Is there a way to accomplish this without listing every single role that needs access, and only specifying the roles that should be prevented from having access?
Here is the code for the class I used to solve this problem. It derives heavily from
AuthorizeAttribute
, and will allow any authenticated user through who does not match the specifications set by the parameters.(Note that the important method is
AuthorizeCore
- everything else is essentially copied or inherited fromAuthorizeAttribute
)You can use it on controllers or actions like any other
AuthorizeAttribute
: