1

I am building a website on an intranet and one of the directories can only be accessed by hard coded authorized users. They are defined in web.config. It looks similar to this.

<location path="admin">
    <system.web>
        <authorization>
            <allow users="user1"/>
            <allow users="user2"/>
            <allow users="user3"/>
            <allow users="user4"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location> 

What I want then is to create a link to this directory which only appears to those users... At the moment, to build the link I'm rechecking there windows usernames and hard coding them in again like this...

<% 
    if (HttpContext.Current.User.Identity.Name == "user1" ||         
        HttpContext.Current.User.Identity.Name == "user2" ||
        HttpContext.Current.User.Identity.Name == "user3" ||
        HttpContext.Current.User.Identity.Name == "user4")
    {
        Response.Write("<a href='admin/Default.aspx'>Admin Site</a>");
    }   
%>

But what I want to do is reference my list from the webiconfig file and say something like

if (HttpContext.Current.User.Identity.Name == // a user from the web.config list

Is this possible and if so can you help me... Thanks

kev670
  • 810
  • 2
  • 18
  • 37

1 Answers1

3

You can get the authorization rules from web.config like this:

            AuthorizationSection configSection =
      (AuthorizationSection)ConfigurationManager.GetSection("system.web/authorization");

        var users = new List<string>();

        var rules = configSection.Rules;

        foreach (AuthorizationRule rule in rules)
        {
            if (rule.Action == AuthorizationRuleAction.Allow)
            {
                foreach (string user in rule.Users)
                {
                    if (!users.Contains(user)) users.Add(user);
                }
            }
        }

But you must also pay atention to the precedence of the rules.

Escobar5
  • 3,941
  • 8
  • 39
  • 62
  • thanks for the answer but what do you mean the precedence of the rules... what am I not paying attention too? – kev670 Aug 16 '12 at 16:36
  • for example if you have a deny rule for user1 and then an allow rule for user1, the first one have precedence over the next one, so the request is denied. – Escobar5 Aug 16 '12 at 16:40