简体   繁体   中英

Programmatically enable or disable anonymous authentication in IIS

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?

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();
        } 

好吧,原来我找不到动态更改身份验证模式的方法,但我找到了解决这个问题的非常巧妙的解决方案:我创建了另一个Web应用程序,将其嵌套在第一个,为其设置了Forms Auth模式第一个和嵌套的Windows,每当我需要使用IIS的权限来处理域,用户组等时,我使用从一个到另一个的重定向,通过cookie传递数据和作为url参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM