Sle*_*ess 0 .net directoryservices active-directory
我正在尝试连接到不同林中的 Active Directory 域 (W2K8R2 DC)。为此,我将凭据传递到以下 DirectoryEntry 构造函数中:
DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType)
Run Code Online (Sandbox Code Playgroud)
这一切都很好。不过,我想做的是以某种方式保留连接,并在对 AD 的所有调用中重复使用它,这样我就不需要重复传递凭据。这有可能吗?
谢谢!
如果您希望在连接级别进行控制,我建议您使用System.DirectoryServices.Protocol。您可以重复使用 LDAP 连接来进行不同的 LDAP 查询。然而,编程范式与DirectoryEntry
如果您需要使用DirectoryEntry,则必须将用户名和密码存储在某处,然后将它们传递给所有对象DirectoryEntry。我要做的就是编写一个方法,并让该方法使用正确的用户名和密码为我GetDirectoryEntry(string dn)创建。DirectoryEntry这看起来不太优雅,但并没有做错什么。如果您希望密码以纯文本形式存储在内存中,请使用SecureString来存储密码。
这没有什么问题,因为DirectoryEntry它维护着自己的 LDAP 连接池。如果您有多个DirectoryEntry具有相同的用户名和密码,它将足够智能地共享 LDAP 连接。它基本上与持有单个 LDAP 连接并执行不同的 LDAP 查询相同。它不会针对每个对象向 LDAP 服务器重新进行身份DirectoryEntry验证
如果您不喜欢依赖 的黑盒功能DirectoryEntry,以下建议的解决方法可能会让您感觉更好。
static DirectoryEntry GetObject(DirectoryEntry root, string dn)
{
using (DirectorySearcher searcher = new DirectorySearcher(root))
{
searcher.Filter = "(distinguishedName=" + dn + ")";
searcher.SearchScope = SearchScope.Subtree;
SearchResult result = searcher.FindOne();
if (result == null) return null;
return result.GetDirectoryEntry();
}
}
Run Code Online (Sandbox Code Playgroud)
您只需使用用户名和密码绑定到根对象即可。然后,您可以将根对象保留为静态变量或任何您喜欢的变量。然后,您可以DirectoryEntry通过执行 LDAP 查询并将该集设置SearchRoot为根对象来获取另一个对象。返回的DirectoryEntry仍将使用 root 的用户名和密码。同样,这并不比简单地将用户名和密码传递给DirectoryEntry. 事实上,从性能角度来看,情况更糟,因为我们需要再执行一次 LDAP 查询来获取DirectoryEntry