3

Is it possible to add location tag dynamically with c# in web config?

for example, I want to add:

  <location path="a/b">
    <system.web>
      <authorization>
        <allow users="xxx"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

The folder b is created on run time, and I want to add an access to the user which created it. The number of the folders created is unknown.

I use forms authentication.

Inbal
  • 909
  • 2
  • 28
  • 46
  • 2
    I'm not sure this can be done, because in most cases, the config file is only read when the process starts. If you even can change it at run time, I am not sure your changes would be picked up. You might be better off implementing a custom security provider that handles the user name and requested route. – SouthShoreAK Oct 29 '13 at 16:28
  • @SouthShoreAK I guess it is like changing authorization or connection string. If you use C# System.Configuration then it is possible. Can you please add a reference for implementing a custom security provider? It can be helpfull. Thanks! – Inbal Oct 29 '13 at 17:36

1 Answers1

1

Like @SouthShoreAK I don't think that can be done in this way, but always there are options, one approach could be by having a base web.config that you can edit an save in each folder that you create in wich you add the authorization that you need, the code that I put below does this.

try
{
    //Load the empty base configuration file
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~/WebEmpty.config");

    //Get te authorization section
    AuthorizationSection sec = config.GetSection("system.web/authorization") as AuthorizationSection;

    //Create the access rules that you want to add
    AuthorizationRule allowRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
    allowRule.Users.Add("userName");
    //allowRule.Users.Add("userName2"); Here can be added as much users as needed
    AuthorizationRule denyRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
    denyRule.Users.Add("*");

    //Add the rules to the section
    sec.Rules.Add(allowRule);
    sec.Rules.Add(denyRule);

    //Save the modified config file in the created folder
    string path = MapPath("~/NewFolder/Web.config");
    config.SaveAs(path);

}
catch (Exception ex)
{
    //Handle the exceptions that could appear
}

Your WebEmpty.config would be like this

<?xml version="1.0"?>
<configuration>
</configuration>

And your saved file looks like this

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authorization>
            <allow users="userName" />
            <deny users="*" />
        </authorization>
    </system.web>
</configuration>

Another thing to consider would be the read/write permission to create the config file, but I think that you already have it because of the dynamic folder creation.

Hope this help.

Dave Rob
  • 46
  • 3