How to control access for specific users in ASP.NET

You can manage set of users, anonymous or authenticated, by using approach described in the article How to define authorization rules in ASP.NET. You can use the <allow> and <deny> rules to specify a user name or a list of comma-separated user names. The next example shows how to use <deny> rule to restrict access for 4 users. These users will not be able to access the pages in the directory having a web.config containing these entries in place. All other authenticated users will be allowed.

<authorization>

<deny users=”?” />

<deny users=”jhon” />

<deny users=”maria” />

<deny users=”susan” />

<deny users=”mike” />

<allow users=”*” />

</authorization>

You can also use a comma-separated list to deny multiple users at once:

<authorization>

<deny users=”?” />

<deny users=”jhon, maria, susan, mike” />

<allow users=”*” />

</authorization>

Important notes:

1. In both these cases the order in which the three users are listed is unimportant, but it is important that these users are denied before you include the <allow> rule. For example, the following authorization rules do not affect the user susan, because ASP.NET matches the rule that allows all users and doesn’t read any further:

<authorization>

<deny users=”?” />

<deny users=”jhon, maria, mike” />

<allow users=”*” />

<deny users=”susan” />

</authorization>

When creating secure applications, the better approach is to explicitly allow specific users or groups and then deny all others (rather than denying specific users, as in the examples so far). Here’s an example of authorization rules that explicitly allow two users. All other user requests will be denied access, even if they are authenticated.

<authorization>

<deny users=”?” />

<allow users=”jhon, mike” />

<deny users=”*” />

</authorization>

2. The format of user names in these examples assumes forms authentication. In forms authentication, you assign a user name when you call the RedirectFromLoginPage() method. At this point, the UrlAuthorizationModule will use that name and check it against the list of authorization rules.

3. Windows authentication is a little different, because names are entered in the format DomainName\UserName or ComputerName\UserName. You need to use the same format when listing users in the authorization rules. For example, if you have the user accounts jhon and mike on a computer named SARABANDA, you can use these authorization rules: