Get AD user 的三种方法

一、 通过AccountManagement 程序集(System.DirectoryServices.AccountManagement)

      acountManagement 包含有:

      1. UserPrincipals

      2. GroupPrincipal

      3.ComputerPrincipals

      4.SearchPrincipals

      我们可以通过GroupPrincipals 方法拿出一组AD user

private static void AccountManagementGetUsers()

{
    var principalContext = new PrincipalContext(ContextType.Domain, "192.168.1.199", "CN=Users,DC=weihu,DC=com", ContextOptions.ServerBind, "administrator", "Password");
    var principals = new GroupPrincipal(principalContext);
    foreach (var members in principals.Members)
   {
       Console.WriteLine(members.DisplayName);
   }

}

二、通过 System.DirectoryServices直接获得ADuser

      在 DirectoryServices 程序中 我们可以使用DirectorySearcher方法获得AD User.

private static void DirectoryConnection()
{
    var directoryEntry = new DirectoryEntry("LDAP://192.168.1.199", "administrator", "Password2");
    var filter = "(&(objectClass=user)(objectCategory=person)(mail=*)(company=Forefront Consulting Group))";
    var propertiesToLoad = new[] { "sAMAccountName", "givenName", "sn", "mail", "userPrincipalName" };
    var directorySearcher = new DirectorySearcher(directoryEntry, filter, propertiesToLoad);

    var users = directorySearcher.FindAll().Cast<SearchResult>();
   foreach (var user in users)
  {
      if (user.Properties.Contains("samaccountname"))
      {
          Console.WriteLine(user.Properties["samaccountname"][0]);
       }
   }
}

三、通过System.DirectoryServices.Protocols拿到AD user

 

private static void LdapConnection()
{
     var server = "Ffazure01.cloudapp.net";
     var userName = "XXX";
     var passsword = "XXX";
     var port = 63600;
     var filter = "Ou=Users,ou=ffcg.local,dc=ffcg,dc=local";
     var propertiesToLoad = new string[] { "sAMAccountName" };
     try
    {
       //AD connection
      var ldapConnection = new LdapConnection(new LdapDirectoryIdentifier(server, port));
      ldapConnection.SessionOptions.SecureSocketLayer = true;
      ldapConnection.SessionOptions.ProtocolVersion = 3;
      ldapConnection.SessionOptions.VerifyServerCertificate = ServerCallback;
      ldapConnection.Credential = new NetworkCredential(userName, passsword);
      ldapConnection.AuthType = AuthType.Negotiate;
      ldapConnection.Bind();
      Console.WriteLine("connection success");
      //GetUser
      const string ldapSearchFilter = "(objectClass=*)";
      var searchRequest = new SearchRequest(filter, ldapSearchFilter, SearchScope.Subtree, propertiesToLoad);
      var searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);

      if (searchResponse == null) return;
      foreach (SearchResultEntry entry in searchResponse.Entries)
     {
         var name = GetStringAttributeValue(entry, "sAMAccountName");
         Console.WriteLine(name);
      }
   }
   catch (Exception e)
   {
       hrow new Exception("Connect AD server error");
    }
}

private static bool ServerCallback(LdapConnection connection, X509Certificate certificate)
{
     return true;
}

private static string GetStringAttributeValue(SearchResultEntry entry, string attribute)

{

try
{
var attrs = entry.Attributes;
if (!attrs.Contains(attribute)) return null;

var directoryAttribute = attrs[attribute];
var attr = directoryAttribute.GetValues(typeof(string)).First() as string ?? "";
return attr;
}
catch (Exception e)
{
    throw new Exception("Could not get attribute " + attribute + "for " + entry.DistinguishedName, e);
}

}

posted @ 2016-08-03 16:17  BeierWu  阅读(1804)  评论(0编辑  收藏  举报