使用LDAP在MVC中进行用户身份验证

时间:2014-05-02 11:56:55

标签: asp.net asp.net-mvc-3 asp.net-mvc-4 ldap

我想使用LDAP(轻量级目录访问协议)进行用户身份验证。我对此没有任何了解。我已经设法为此编写了一些代码,但问题是当我使用用户名签名时和密码出现在我的数据库即用户表我无法登录。但是当我使用LDAP的用户名和密码时,我能够登录到应用程序 我的代码如下:

public ActionResult Login(APPUser model, string returnUrl)
  {
    try
      {
       using (PrincipalContext pc = new PrincipalContext(ContextType.Domain,"10.0.0.100"))
             {
               if (pc.ValidateCredentials(model.UserID, model.Password))
                  {
                     FormsAuthentication.SetAuthCookie(model.UserID, false);
                     return RedirectToAction("Index", "Home");
                   }
              }
              if (Membership.ValidateUser(model.UserID, model.Password))
                {
                  FormsAuthentication.SetAuthCookie(model.UserID, false);
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                }
                 else
                    {
                        ModelState.AddModelError("", "Login failed");
                    }
                }
     catch
        {
        }
          //GetErrorsFromModelState();
                return View(model);

}

Web.Config

    <connectionStrings>
        <add name="ADConnectionString" connectionString="LDAP://"XXXXXXX":389/DC=XXXX,DC=XXX" />
</connectionStrings>
    <system.web>
        <authentication mode="Forms">
          <forms name=".ADAuthCookie" loginUrl="~/Auth/Login" timeout="2880"/>
        </authentication>
 <membership defaultProvider="ADMembershipProvider">
    <providers>
       <clear />
         <add name="ADMembershipProvider" 
                 type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
                 connectionStringName="ADConnectionString"
                  connectionProtection="Secure"
                  connectionUsername="admin"
                  connectionPassword="admin234"
                  attributeMapUsername="sAMAccountName"
                  enableSearchMethods="false" />
          </providers>
</membership>

请尽力帮助我。

1 个答案:

答案 0 :(得分:4)

AD(Active Directory)是一个目录服务提供程序(在Windows环境中提供身份验证,目录,策略和其他服务的系统)。

LDAP(轻量级目录访问协议)是一种为目录服务提供商设计的协议,用于查询和修改AD等目录服务提供程序中的项目,AD支持一种LDAP形式。

换句话说,您使用LDAP从AD中检索信息。

现在,如果您需要针对Windows域(AD)实施Intranet用户身份验证,那么您需要阅读Integrated Windows Authentication。要启用它通常需要

  • 设置IIS以进行集成Windows身份验证
  • 设置asp.net应用程序

并可选择在IE中启用集成Windows身份验证。阅读更多here

完成后,用户将自动登录而无需输入登录名或密码。您将能够从AD获得他的身份(User.Identity.Name)和其他属性。

这是一种安全的身份验证形式,您可以在使用SharePoint,Outlook Web Access或类似的Intranet应用程序时看到。