Programmatically enable or disable anonymous authe

2020-04-12 09:05发布

I have a web application and I need to provide its users the option to switch login method from FormsAuth to WindowsAuth. I managed to change the web.config file via code:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Url.Content("~"));
AuthenticationSection auth = ((AuthenticationSection)(config.SectionGroups["system.web"].Sections["authentication"]));
auth.Mode = AuthenticationMode.Windows; // Or Forms if I want to.
config.Save();

But the problem is, when I use FormsAuth, I need the Anonymouse Authentication option to be turned on, and when I use WinAuth, I need it to be off. And I just cannot find the way to change that option via code.

Everything on the internet says to do this:

<security>
 <authentication>
  <anonymousAuthentication enabled="false/true" />
 </authentication>
</security>

But when I insert this into my webapp's web.config it says that configuration is wrong. Than I read this might work in another config file, like appHost.config or something like that but I prefer to make changes only to my own application and not to IIS I hope you understand why.

So, how can I do that?

2条回答
我想做一个坏孩纸
2楼-- · 2020-04-12 09:26

You are trying to update wrong section. anonymousAuthentication is part of system.webServer and not system.web. Correct configuration is

<system.webServer>
<security>
  <authentication>
    <anonymousAuthentication enabled="true" />
  </authentication>
</security>
</system.webServer>

You can modify it using ServerManager class found in Microsoft.Web.Administration. Search for nugget package "Microsoft.Web.Administration". Once you have added reference to Microsoft.Web.Administration.dll using nugget you can modify it using code as follows:

        using (ServerManager serverManager = new ServerManager())
        {
            Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
            Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
            anonymousAuthenticationSection["enabled"] = true;                
            serverManager.CommitChanges();
        } 
查看更多
smile是对你的礼貌
3楼-- · 2020-04-12 09:26

Okay, so, turned out I could not find a way to dynamically change the auth mode, but I found pretty neat solution to the problem: I have created another web application, nested it inside the first one, had set Forms Auth mode for the first one and Windows for the nested and whenever I needed to use IIS's power to work with domain, user groups etc, I used a redirect from one to another, passing data by cookies and as url parameters.

查看更多
登录 后发表回答