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

时间:2013-09-19 19:04:08

标签: c# asp.net authentication forms-authentication windows-authentication

我有一个正常运行的.NET MVC应用程序,它使用Windows身份验证。由于我们使用共享计算机,Windows身份验证对我们不起作用;我们需要切换到Forms身份验证,但我们仍然希望针对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>

2 个答案:

答案 0 :(得分:6)

您有两种选择。一,使用提供商并利用内置框架基础设施。二,使用目录服务并自行编码。后者将为您提供完全控制和灵活性。前者将为您提供易于实施的功能。

使用提供商:

(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" />,以启用用户帐户的访问权限,而不是应用程序池身份。您还需要在IIS中设置anonymous身份验证。

修改

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

答案 1 :(得分:0)

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