Search code examples
c#asp.net-mvcasp.net-mvc-5membership-providerroleprovider

How to add a .Net MVC request filter to prevent action calls based on role membership?


In .Net MVC5, how would one add a request filter to prevent action calls based on role membership?

See this comment:

wouldn't it make more sense to use a request filter to prevent the action call on the controller in the event that the current user did not have the right role membership instead of trying to mix the auth logic in to the business logic?

Thank you.


Solution

  • My best solution for this is using: [AuthorizeAttribute]

    You can place it as a normal attribute is used in c# mvc, like for ex:

     [Authorize]
     public ActionResult AuthenticatedUsers()
     {
         return View();
     }
    

    You can also use it in top of the controller like this:

    [Authorize]
     public class HomeController : Controller
     {
     }
    

    And if you want it do be depedent on roles, you just simple give one parameter to this attribute like this:

    [Authorize(Roles = "Admin, Super User")]
     public ActionResult AdministratorsOnly()
     {
         return View();
     }
    
     [Authorize(Users = "Betty, Johnny")]
     public ActionResult SpecificUserOnly()
     {
         return View();
     }
    

    Here is some more detailed information for your question which I'd suggest would help you alot.

    Good luck!