Search code examples
asp.net-mvcauthenticationiisforms-authenticationwindows-authentication

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?


Solution

  • 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.