2012-08-14 62 views
0

結構是這樣,驗證用戶在LDAP目錄

ou=system,ou=valeteck,cn=mayank 

我必須檢查用戶輸入的密碼是正確的,並配以mayank的用戶的密碼即。

但系統和cn='mayank'有不同的密碼。如果我創建的目錄輸入對象的密碼爲cn,我沒有使用ldap進行身份驗證,但是如果使用系統目錄及其密碼,我會進行身份驗證,但是如何檢查用戶的密碼。

+0

可能重複的[如何在.NET中驗證LDAP](http://stackoverflow.com/questions/769268/how-to-authenticate-ldap-in-net) – Shai 2012-08-14 12:53:24

+0

[我的迴應在這裏有幫助嗎? ](http://stackoverflow.com/questions/290548/c-sharp-validate-a-username-and-password-against-active-directory/499716#499716) - 這是專門爲Active Directory – 2012-08-14 14:57:17

回答

0
private bool LoginS(string userName, string password) 
     { 
      bool authentic = false; 
      try 
      { 
       DirectoryEntry entry = new DirectoryEntry(LDAP-Path, userName, password, AuthenticationTypes.Secure); 
       authentic = true; 


       Console.WriteLine("Authentication successful"); 

      } 
      catch (DirectoryServicesCOMException e) 
      { 
       _logger.Error("Authentification error", e); 
       //User doesnt exist or input is false 

      } 
      return authentic; 
     } 
0

甚至有更簡單的方法由Windows API使用advapi32.dll提供給您。

例子:

[DllImport("advapi32.dll", EntryPoint = "LogonUserW", SetLastError = true, CharSet = CharSet.Auto)] 
    public static extern bool LogOnUser(string lpszUserName, string lpszDomain, string lpszPassword, 
     int dwLogOnType, int dwLogOnProvider, ref IntPtr phToken); 

如果用戶確實是在域和正確輸入它的密碼這種方法簡單地返回true或false。 然後,您只需製作自己的登錄方法即可檢查針對advapi32.dll的身份驗證。

public ActionResult SignIn(SignInModel model) 
    { 
     string domainName = CheckSignIn.GetDomainName(model.User.UserName); 
     string userName = CheckSignIn.GetUserName(model.User.UserName); 
     IntPtr token = IntPtr.Zero; 
     bool result = CheckSignIn.LogOnUser(userName, domainName, model.User.UniqueUserCode, 2, 0, ref token); 
     if (result) 
     { 
      if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]) && Request.QueryString["ReturnUrl"] != "/") 
      { 
       FormsAuthentication.RedirectFromLoginPage(model.User.UserName, false); 
      } 
      else 
      { 
       FormsAuthentication.SetAuthCookie(model.User.UserName, false); 
       return RedirectToAction("MyVoyages", "Voyage"); 
      } 
     } 
     return SignIn(true); 
    } 

簡單,但功能強大。