以编程方式启用或禁用IIS中的匿名身份验证

时间:2015-02-09 21:03:25

标签: asp.net-mvc authentication iis forms-authentication windows-authentication

我有一个Web应用程序,我需要为其用户提供将登录方法从FormsAuth切换到WindowsAuth的选项。我设法通过代码更改web.config文件:

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

但问题是,当我使用FormsAuth时,我需要打开Anonymouse Authentication选项,当我使用WinAuth时,我需要它关闭。我只是找不到通过代码更改该选项的方法。

互联网上的一切都说要做到这一点:

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

但是当我将其插入我的webapp的web.config时,它说配置错误。比我读到的这可能在另一个配置文件中工作,比如appHost.config或类似的东西,但我更喜欢只对我自己的应用程序而不是IIS进行更改我希望你理解为什么。

那么,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您正在尝试更新错误的部分。 anonymousAuthentication是system.webServer的一部分,而不是system.web。正确的配置是

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

您可以使用Microsoft.Web.Administration中的ServerManager类对其进行修改。搜索nugget包“Microsoft.Web.Administration”。使用nugget添加对Microsoft.Web.Administration.dll的引用后,您可以使用以下代码对其进行修改:

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

答案 1 :(得分:1)

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

相关问题