【问题标题】:get active directory container objects for new user获取新用户的活动目录容器对象
【发布时间】:2011-01-24 03:37:01
【问题描述】:
我想在一个可以添加新用户的活动目录域中创建一个容器对象树。我可以通过域递归并获取目录中的所有内容,但我想将我的范围限制为仅对用户有效的容器。
LDAP 查询会如何获取适合用户对象的节点的子节点?有没有更好的方法来做到这一点?
如果你好奇的话,我正在使用 c#、System.DirectoryServices 和 .net 3.5。
谢谢!
【问题讨论】:
标签:
c#
active-directory
ldap
directoryservices
【解决方案1】:
如果您还没有,请查看优秀的 MSDN article Managing Directory Security Principals in the .NET Framework 3.5,了解如何在 .NET 3.5 中使用 System.DirectoryServices.AccountManagement 中的新功能。
为了绑定到您的容器,您需要知道它的 LDAP 路径,然后您可以基于该容器建立上下文:
PrincipalContext ctx =
new PrincipalContext(ContextType.Domain, "Fabrikam",
"ou=TechWriters,dc=fabrikam,dc=com");
有了这个上下文,你现在可以例如在该上下文中搜索某些类型的主体:
// create a principal object representation to describe
// what will be searched
UserPrincipal user = new UserPrincipal(ctx);
// define the properties of the search (this can use wildcards)
user.Enabled = false;
user.Name = "user*";
// create a principal searcher for running a search operation
PrincipalSearcher pS = new PrincipalSearcher();
// assign the query filter property for the principal object you created
// you can also pass the user principal in the
// PrincipalSearcher constructor
pS.QueryFilter = user;
// run the query
PrincipalSearchResult<Principal> results = pS.FindAll();
Console.WriteLine("Disabled accounts starting with a name of 'user':");
foreach (Principal result in results)
{
Console.WriteLine("name: {0}", result.Name);
}
这对你有用吗?这就是你要找的吗?
【解决方案2】:
如果我正确理解您的问题,您想知道 Active Directory 中什么样的对象可以包含 User 对象。
我想你可以从 AD 架构分区中得到答案。我快速检查了运行 Windows 2003 AD 的架构分区。 User 对象允许分配给 OU、container、builtinDomain 和 domainDNS.
我没有检查 Windows 2008,但我相信它应该是一样的。很多人都知道OU和container是什么。很少有人知道 builtinDomain 和 domainDNS 是什么。我怀疑它对你的情况是否有用。 builtinDomain 是用于包含内置帐户的特殊容器。默认情况下,AD 在CN=Builtin,DC=yourdomain,DC=com 创建了一个builtinDomain。 domainDNS 是您的根域路径DC=yourdomain,DC=com。
这是一个在特定节点下的Active Directory中查找各种对象的函数。如果您认为 builtinDomain 和 domainDNS 在您的情况下没有意义,只需将其从 LDAP 过滤器中取出即可。
IEnumerable<DirectoryEntry> FindUserParentObject(DirectoryEntry root)
{
using (DirectorySearcher searcher = new DirectorySearcher(root))
{
searcher.Filter = "(|(objectClass=organizationalUnit)(objectClass=container)(objectClass=builtinDomain)(objectClass=domainDNS))";
searcher.SearchScope = SearchScope.Subtree;
searcher.PageSize = 1000;
foreach (SearchResult result in searcher.FindAll())
{
yield return result.GetDirectoryEntry();
}
}
}