2012-02-27 47 views
0

我已經爲Active Directory LDAP用戶認證編寫了代碼,它對AD中的所有用戶帳戶進行了認證,但我只想管理員帳戶認證而不是其他用戶帳戶(請參見下面的代碼)。命名連接DNS(參見附件圖片)的僅用於管理員帳戶的LDAP認證

 try 
     { 
      DirectoryEntry entry = new DirectoryEntry(Domain, UserName, Password); 
      object nativeObject = entry.NativeObject; 
      Program.fileWrite.WriteLine(DateTime.Now + "\t Login with credentials " + UserName + " and " + Password); 
      return true; 
     } 
     catch (DirectoryServicesCOMException e) 
     { 
      Program.fileWrite.WriteLine(DateTime.Now + "\t " + e.Message); 
      return false; 
     } 

login page

回答

2

試試這個代碼:

public static bool ValidateCredential(string domain, string userName, string password) 
    { 
     using (var context = new PrincipalContext(ContextType.Domain, domain)) 
     { 
      using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName)) 
      { 
       if (user == null) return false; 

       using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Admins")) 
       { 
        if (group == null) return false; 

        foreach (var member in group.GetMembers()) 
        { 
         if (member.Sid.Equals(user.Sid)) 
         { 
          return context.ValidateCredentials(userName, password); 
         } 
        } 
       } 
      } 
     } 

     return false; 
    } 
+0

感謝。它的工作原理非常酷 – soundy 2012-02-28 05:27:46