通过LDAP连接到Active Directory

War*_*ild 44 c# active-directory

我想用C#连接到我们的本地Active Directory.

我发现这篇文章很好.

但我真的不知道如何通过LDAP连接.

有人可以解释如何使用询问的参数吗?

示例代码:

  static DirectoryEntry createDirectoryEntry()  
  {  
     // create and return new LDAP connection with desired settings  

     DirectoryEntry ldapConnection     = new DirectoryEntry("rizzo.leeds-art.ac.uk");  
     ldapConnection.Path               = "LDAP://OU=staffusers,DC=leeds-art,DC=ac,DC=uk";  
     ldapConnection.AuthenticationType = AuthenticationTypes.Secure;  
     return ldapConnection;  
  }  
Run Code Online (Sandbox Code Playgroud)

我只有Active Directory服务器的主机名和IP地址.什么DC=xxx,DC=xx等等意味着什么?

The*_*ger 86

DC是您的域名.如果你想连接到域example.com而不是你的dc:DC = example,DC = com

您实际上不需要域控制器的任何主机名或IP地址(可能有很多).

试想一下,你正在连接到域名本身.因此,要连接到域example.com,您只需编写即可

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
Run Code Online (Sandbox Code Playgroud)

而且你已经完成了.

您还可以指定用于连接的用户和密码:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
Run Code Online (Sandbox Code Playgroud)

还要确保始终以大写形式编写LDAP.我遇到了一些麻烦和奇怪的异常,直到我读到某个地方我应该尝试用大写字母写它并解决了我的问题.

directoryEntry.Path属性允许您深入了解您的域.因此,如果要搜索特定OU(组织单位)中的用户,可以在那里进行设置.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";
Run Code Online (Sandbox Code Playgroud)

这将匹配以下AD层次结构:

  • COM
      • 用户
        • 所有用户
          • 特定用户

只需将层次结构从最深层写入最高层即可.

现在你可以做很多事情了

例如,按帐户名称搜索用户并获取用户的姓氏:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}
Run Code Online (Sandbox Code Playgroud)

  • 将"LDAP://example.com"替换为"LDAP://myDomainController.example.com".应该工作并连接到指定的域控制器. (2认同)