How to control access for specific roles in ASP.NET

If you need to manage an enterprise application that supports thousands of users and you need to define permissions for each individual user, it would be exhausting, difficult to change, and nearly impossible to complete without error. The easiest way to maintain the users is to group them into categories called roles.

In Windows authentication (described in the article How does Windows authentication work in ASP.NET), roles are automatically available and naturally integrated Windows groups. In this case you can use built-in groups (such as Administrator, Guest, PowerUser, and so on), or you can create your own to represent application-specific categories (such as Manager, Supplier, Controller, and so on).

Once you have defined roles, you can create authorization rules that act on these roles.  In fact, these rules look essentially the same as the user-specific rules described in the article How to control access for specific users in ASP.NET.

For example, the following authorization rules deny all anonymous users, allow two specific users (mike, john and tina), and allow two specific groups (Manager and Supplier). All other users are denied.

<authorization>

<deny users=”?” />

<allow users=”THEDOMAIN\mike, THEDOMAIN\john,THEDOMAIN\tina” />

<allow roles=” THEDOMAIN\Manager,THEDOMAIN\Supplier” />

<deny users=”*” />

</authorization>

Using role-based authorization rules is simple conceptually, but rule ordering is important. Consider this example:

<authorization>

<deny users=”?” />

<allow users=” THEDOMAIN\mike” />

<deny roles=” THEDOMAIN\Guest” />

<allow roles=” THEDOMAIN\Manager” />

<deny users=” THEDOMAIN\john” />

<allow roles=” THEDOMAIN\Supplier” />

<deny users=”*” />

</authorization>

ASP.NET parses these rules:

– The user mike is allowed, regardless of the group to which he belongs.

– All users in the Guest role are then denied. If mike is in the Guest role, mike is still allowed because the user-specific rule is matched first.

– All users in the Manager group are allowed. The only exception is users who are in both the Manager and Guest groups. The Guest rule occurs earlier in the list, so those users would have already been denied.

– The user john is denied access, but if john belongs to the allowed Manager group, john will already have been allowed, because this rule won’t be executed.

– Any users who are in the Supplier group, and who haven’t been explicitly allowed or denied by one of the preceding rules, are allowed.

– Finally, all other users are denied.

You should keep in mind that these overlapping rules can also span multiple directories. For example, a subdirectory might deny a user, while a parent directory allows a user in that group. In this example, when accessing files in the subdirectory, the user-specific rule is matched first.