5

我有一个使用 Windows 身份验证的正常运行的 .NET MVC 应用程序。由于我们使用共享计算机,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>
4

2 回答 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) 你很高兴。

笔记:

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

另请注意,您可能需要处理更多事情<identity impersonate="true" />,例如启用从用户帐户而不是应用程序池身份进行访问。您还需要anonymous在 IIS 中设置身份验证。

编辑:

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

于 2013-09-24T12:45:24.077 回答
0

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

于 2013-09-19T19:36:42.297 回答