Search code examples
c#asp.net-mvcrazorrole-based-access-control

Role base access on UI controls in ASP.NET MVC


I am building an application where same page can be visited by multiple user of different roles, for example

  • Administrator can update all fields
  • Initiator can insert data in all controls of the page except comments box
  • Reviewer can only insert data in comments box
  • Guide can only read data on the screen, no access to update anything on screen

Only thing that came in my mind so far is that I should make custom Html helpers where I will accept role as a parameter and check the role and accordingly add disable or enable classes to the control. Application will have hundreds of pages, but some pages might have different access to different roles. Please provide a solution where I can achieve this specific page & role base access control and without much compromising with performance.

Any help or suggestion will be appreciated. Thank you.


Solution

  • Do you really want to hide the controls that a user is not authorized to update? Or simply show unauthorized error (return new HttpUnauthorizedResult();) when they hit the save/update button. If you prefer the latter, here is one way of doing this:

    1. Your razor views will not use any authorization code.
    2. Create a group/role something like "All Authorized X app"
    3. Create groups/roles for individual functions, like "X Administrators", "X Initiators", "X Reviewers" and "X Guides"
    4. Add all groups/roles in third bullet into the second one
    5. Decorate your controllers like [Authorize ("Roles="All Authorized X app")]
    6. Within your save/update actions, use if(User.IsInRole("X Administrators")) or if(User.IsInRole("X Reviewer"))