Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC Role manager

I am using role manager and windows authentication for my asp.net mvc project we have 2 Roles which are viewers and Editors .

    <authentication mode="Windows" />
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
        <providers>
          <clear />
          <add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </providers>
    </roleManager>

Editor can access the whole application but Viewer can only access two actions

I first tried to put Authorize attribute for base controller which just allow editor to access everything :

[Authorize(Roles = "Editors")]
public class BaseController : Controller

and then add Authorize attribute to those two action:

[Authorize(Roles = "Viewers,Editors")]
public ActionResult Report(PaymentsUnallocatedAndQueriedModel model)

it does not work ,it does not allow viewer to access any action which make sense now.

I believe it is not a good idea to repeat Authorize attribute on the top of each action.

Could you please tell me if there is a better solution to that

like image 367
Elham Avatar asked Aug 29 '12 13:08

Elham


1 Answers

You have to look at this from a tree perspective. In order to get to an action, you must first be able to get to a controller. In this case, you've restricted the controller to the Editors group, so Viewers can't even get that far. What would most likely be more helpful would be to restrict the controller to Viewers, Editors and then in the actions that require Editor only permission, specify those. This will generate redundant attributes, but consider the code cost if you had to manually restrict each action based on role membership.

[Authorize(Roles = "Viewers, Editors")]
public class BaseController : Controller
{

    [Authorize(Roles = "Editors")]
    public ActionResult EditReport(PaymentsUnallocatedAndQueriedModel model)
    {
        // Some editor only functionality
    }

    public ActionResult Report(PaymentsUnallocatedAndQueriedModel model)
    {
        // Some functionality for both. No attribute needed
    }
}
like image 188
Joel Etherton Avatar answered Sep 21 '22 07:09

Joel Etherton