.NET:从Windows身份验证更改为基于AD的表单身份验证

5
我有一个功能良好的.NET MVC应用程序,使用Windows身份验证。由于我们使用共享计算机,Windows身份验证对我们无效;我们需要切换到Forms身份验证,但我们仍然希望针对Active Directory进行身份验证。我已经阅读了各种有关此主题的教程,但这些教程似乎都不起作用,并且没有显示如何将现有的Windows身份验证应用程序转换为使用Forms身份验证针对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>
2个回答

7
你有两个选择。第一,使用提供商并利用内置的框架基础设施。第二,使用目录服务并自己编写代码。后者将为您提供完全的控制和灵活性。前者将为您提供实现的便利。
使用提供商: (1) 在您的web.config中指定forms-auth:
<authentication mode="Forms">
    <forms name=".ADAuthCookie" loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" timeout="05"/>
</authentication>

(2) 添加LDAP连接字符串:

<connectionStrings>
    <add name="ADConnectionString" connectionString="LDAP://fqdn.co/DC=fqdn,DC=co"/>
</connectionStrings>

(3) 添加成员资格提供程序(将连接字符串名称提供为上面定义的那个):

<membership defaultProvider="MyADMembershipProvider">
    <providers>
        <add name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, 
        Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
    </providers>
</membership>

对于提供者,您需要根据ASP.Net版本找到令牌和版本号。

(4) 创建一个登录页面(按照forms-auth loginurl指定的Login.aspx),并使用asp.net的登录控件:

<asp:Login ID="LoginUser" runat="server" ....

(5) 一切准备就绪。

自己动手:

(1) 在您的web.config中指定forms-auth:

<authentication mode="Forms">
    <forms name=".MyAuth" loginUrl="~/Logon.aspx" defaultUrl="~/Default.aspx" timeout="05">   
    </forms>
</authentication>

(2) 获得对 System.DirectoryServicesSystem.DirectoryServices.AccountManagement 的引用。

(3) 在您的逻辑层中创建身份验证方法(类似以下内容):

<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

上面的代码片段是VB语言编写的,因为我对C#不太有信心,但你已经理解了。

(4) 创建一个登录页面,并在后台代码中调用此方法:

isAuthenticated = LogicLayer.Authenticate(domainName, userName, userPassword)

(5) 如果验证成功,即isAuthenticated返回true,则设置forms-auth cookie:

FormsAuthentication.SetAuthCookie(userName, isRememberMe)

(6) 操作完成,您可以继续进行。

注意:

请注意使用表单身份验证将使凭据以纯文本形式在网络上传输,从而带来安全隐患。您需要自己采取适当的安全措施。SSL 可以提供最简便的帮助。

另外,请注意,您可能需要处理一些其他事情,例如启用<identity impersonate="true" /> 以允许从用户账户而不是应用程序池标识访问等。您还需要在 IIS 中设置 anonymous 身份验证。

编辑:

我之前没有注意到您的应用程序是 MVC 应用程序。上面的某些点是 WebForms 特定的(比如控件和代码后台)。所以,请忽略那些内容。否则,我希望您能理解其背后的思想。


嗨,感谢您的回复!我已经成功解决了这个问题。如果您能编辑您的答案以更准确地反映MVC,我将很乐意授予您奖励。 - James Harpe

0

前往ASP.NET配置网页,然后进入安全选项卡,您应该能够从那里进行设置。


这并不能帮助我设置它以对接Active Directory进行身份验证。 - James Harpe
你有没有看过这个?我还没有完全阅读它,因为我刚找到它,但听起来它可能会满足你的需求。http://support.microsoft.com/kb/316748/en-us - Jeoffrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接