How to define authorization rules in ASP.NET

You can define the authorization rules in the <authorization> element within the <system.web> section of  the web.config file. The basic structure is as follows:

 

<authorization>

<allow users=”comma-separated list of users”

roles=”comma-separated list of roles”

verbs=”comma-separated list of verbs” />

<deny users=”comma-separated list of users”

roles=”comma-separated list of roles”

verbs=”comma-separated list of verbs” />

</authorization>

 

There are two types of rules: allow and deny. You can add as many allow and deny rules as you want and each rule rule identifies one or more users or roles (groups of users). You can use the verbs attribute to create a rule that applies only to specific types of HTTP requests: GET, POST, HEAD and DEBUG.

You can deny access to all anonymous users, by using a question mark (?) as a wildcard which represents all users with unknown identities in a <deny> rule like this:

<authorization>

<deny users=”?” />

</authorization>

This rule is almost always used in authentication scenarios, because you can’t specifically deny other, known users unless you first force all users to authenticate themselves.

You can allow access to all authenticated and anonymous users, by using an asterisk (*) as a wildcard in a <allow> rule like this:

<authorization>

<allow users=”*” />

</authorization>

Note: This rule is rarely required, because it’s already present in the machine.config file.  After ASP.NET applies all the rules in the web.config file, it applies rules from the machine.config file. As a result, any user who is not explicitly denied access automatically gains access.

 

Important notice:

You can add more than one rule in <authorization> section.

In case if the section is like this:

<authorization>

<allow users=”*” />

<deny users=”?” />

</authorization>

ASP.NET scans through the list from top to bottom, when evaluating rules and soon as it finds an applicable rule, it stops its search. In this case, ASP.NET determines that the rule <allow users=”*”> applies to the current request and does not evaluate the second line.  If you reverse the order of these two lines you will deny anonymous users (by matching the first rule) and allow all other users (by matching the second rule).

<authorization>

<deny users=”?” />

<allow users=”*” />

</authorization>

When you add authorization rules to the web.config file in the root directory of the web application, the rules automatically apply to all the web resources that are part of the application:

1. If you’ve denied anonymous users, ASP.NET will examine the authentication mode.

2. If you’ve selected forms authentication, ASP.NET will direct the user to the login page.

3. If you’re using Windows authentication, IIS will request user credentials from the client browser, and a login dialog box may appear (depending on the protocols you’ve enabled).