C# .NET:从Windows身份验证更改为针对AD的窗体身份验证

C# .NET:从Windows身份验证更改为针对AD的窗体身份验证,c#,asp.net,authentication,forms-authentication,windows-authentication,C#,Asp.net,Authentication,Forms Authentication,Windows Authentication,我有一个运行正常的.NET MVC应用程序,它使用Windows身份验证。由于我们使用共享计算机,Windows身份验证将不适用于我们;我们需要切换到表单身份验证,但我们仍然希望针对Active Directory进行身份验证。我已经阅读了有关此主题的各种教程,但这些教程似乎都不起作用,也没有一个说明如何将现有的Windows身份验证应用程序转换为使用针对AD的窗体身份验证的应用程序。我需要做什么来进行此转换 以下是我的应用程序的web.config: <configuration>

我有一个运行正常的.NET MVC应用程序,它使用Windows身份验证。由于我们使用共享计算机,Windows身份验证将不适用于我们;我们需要切换到表单身份验证,但我们仍然希望针对Active Directory进行身份验证。我已经阅读了有关此主题的各种教程,但这些教程似乎都不起作用,也没有一个说明如何将现有的Windows身份验证应用程序转换为使用针对AD的窗体身份验证的应用程序。我需要做什么来进行此转换

以下是我的应用程序的web.config:

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Wellness.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Wellness-20130715090235;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Wellness-20130715090235.mdf" providerName="System.Data.SqlClient" />
    <add name="tt" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=tt-20130805140115; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|tt-20130805140115.mdf" providerName="System.Data.SqlClient" />
    <add name="WellnessEntities" connectionString="metadata=res://*/Models.WellnessModel.csdl|res://*/Models.WellnessModel.ssdl|res://*/Models.WellnessModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MSSQL;initial catalog=Wellness;persist security info=True;user id=Wellness_User;password=xGopher2008;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

  <system.web>
    <httpRuntime maxRequestLength="10240"/>
    <customErrors mode="Off"></customErrors>

    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <authentication mode="Windows" />
    <authorization>
      <allow roles="b-hive\AllStaff"/>
      <deny users="*"/>

    </authorization>
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <applicationSettings>
    <Wellness.Properties.Settings>
      <setting name="Setting" serializeAs="String">
        <value />
      </setting>
    </Wellness.Properties.Settings>
  </applicationSettings>

</configuration>


转到ASP.NET配置网页,然后转到安全选项卡,您应该可以从那里进行设置。

您有两个选项。第一,使用提供者并利用内置的框架基础设施。第二,使用目录服务,自己编写代码。后者将为您提供完全的控制和灵活性。前者将使您易于实现

使用提供者:

(1) 在web.config中指定表单身份验证:

<authentication mode="Forms">
    <forms name=".ADAuthCookie" loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" timeout="05"/>
</authentication>
<authentication mode="Forms">
    <forms name=".MyAuth" loginUrl="~/Logon.aspx" defaultUrl="~/Default.aspx" timeout="05">   
    </forms>
</authentication>
上面的代码片段是用VB编写的,因为我对C#不是很有信心,但你明白了

(4) 创建登录页面并在从代码隐藏处登录时调用此方法:

isAuthenticated = LogicLayer.Authenticate(domainName, userName, userPassword)
(5) 如果成功,即isAuthenticated返回true,则设置表单验证cookie:

FormsAuthentication.SetAuthCookie(userName, isRememberMe)
(6) 你可以走了

注意:

请注意,使用forms auth将使您面临安全隐患,因为凭据将以文本形式通过网络传输。你必须自己采取适当的安全措施。SSL将以最简单的方式帮助您

还要注意的是,您可能还需要处理一些事情,如
,以启用从用户帐户而不是从应用程序池身份进行访问。您还需要在IIS中设置
anonymous
auth

编辑:


我之前没有注意到你的是MVC应用程序。上面的一些要点是特定于WebForms的(如控件和代码落后)。所以,请忽略这一点。否则,我希望你能理解它背后的想法。

这无助于我将其设置为针对Active Directory进行身份验证。你有没有阅读过这篇文章?我还没有完全阅读过,因为我刚刚找到它,但听起来它可能会满足你的需要。嗨,谢谢你的回复!事实上,我已经能够弄明白这一点了。如果您能编辑您的答案,以更准确地反映MVC,我将很高兴授予您奖金。
<authentication mode="Forms">
    <forms name=".MyAuth" loginUrl="~/Logon.aspx" defaultUrl="~/Default.aspx" timeout="05">   
    </forms>
</authentication>
<DirectoryServicesPermission(Security.Permissions.SecurityAction.LinkDemand, Unrestricted:=True)> _
Public Shared Function Authenticate(ByVal domainName As String, ByVal userAlias As String, ByVal userPassword As String) As Boolean
    Try
        Dim context As PrincipalContext = New PrincipalContext(ContextType.Domain, domainName)
        If context.ValidateCredentials(userAlias, userPassword, ContextOptions.Negotiate) Then
            Return True
        Else
            Return False
        End If
    Catch ex As Exception
        Throw
    End Try
End Function
isAuthenticated = LogicLayer.Authenticate(domainName, userName, userPassword)
FormsAuthentication.SetAuthCookie(userName, isRememberMe)