Programmatically enable or disable anonymous authentication in IIS

前端 未结 2 390
梦如初夏
梦如初夏 2021-01-20 05:23

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:

相关标签:
2条回答
  • 2021-01-20 05:28

    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();
            } 
    
    0 讨论(0)
  • 2021-01-20 05:35

    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.

    0 讨论(0)
提交回复
热议问题