简体   繁体   English

C# - 从 Active Directory 返回自定义安全组

[英]C# - Return Custom Security Groups from Active Directory

I currently have the following code which successfully gets all Security Groups from AD and adds them into a Check List box:我目前有以下代码,它成功地从 AD 获取所有安全组并将它们添加到检查列表框中:

try
{
    Logging.LogMessageToFile("Reading Security Groups from AD.");
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
    PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

    foreach (var found in srch.FindAll())
    {
        lstAdGroups.Items.Clear();
        lstAdGroups.Items.Add(found);     
    }
}
catch (Exception ex)
{
    Logging.LogMessageToFile("Unexpected error reading Security Groups from AD: " + ex.Message);
}

My issue is that it currently pulls every Security Group (where ideally I'd only like to only list custom created security groups (eg, exclude any from the Users or Builtin OU's). I can't see if there are any properties against groups to filter 'custom' from out the box. Is this even possible?我的问题是它目前会提取每个安全组(理想情况下我只想列出自定义创建的安全组(例如,从用户或内置 OU 中排除任何安全组)。我看不到是否有针对组的任何属性从开箱即用中过滤“自定义”。这甚至可能吗?

PrincipalSearcher can only filter based on attributes that are exposed in properties of the various Principal classes. PrincipalSearcher只能根据在各种Principal类的属性中公开的属性进行过滤。 If you're looking for groups, you're limited to filtering based on the properties of the GroupPrincipal class.如果您要查找组,则只能根据GroupPrincipal类的属性进行过滤。

That issues aside, filtering out objects in certain OUs isn't something you can do in a query at all simply because there is no AD attribute that contains the OU that you're allowed to filter on.撇开这个问题不谈,过滤掉某些 OU 中的对象根本不是您可以在查询中执行的操作,因为没有包含您可以过滤的 OU 的 AD 属性。 So there is two ways you can do this:所以有两种方法可以做到这一点:

  1. Do what you're already doing, but in your loop, look at the DistinguishedName property of the result.做你已经在做的事情,但在你的循环中,查看结果的DistinguishedName属性。 If it's in an OU you don't like, then just continue;如果它在您不喜欢的 OU 中,则continue; . .

  2. You can use DirectorySearcher directly (which is what PrincipalSearcher uses in the background anyway), and filter by the isCriticalSystemObject attribute.您可以直接使用DirectorySearcher (无论如何PrincipalSearcher在后台使用它),并通过isCriticalSystemObject属性进行过滤。 That will filter out built-in objects like the Domain Admins and Users groups, etc.这将过滤掉Domain AdminsUsers组等内置对象。

Here is a simple example using DirectorySearcher that just outputs the name of each group:这是一个使用DirectorySearcher的简单示例,它只输出每个组的名称:

var searcher = new DirectorySearcher("(&(objectClass=group)(!isCriticalSystemObject=TRUE))");

using (var results = searcher.FindAll()) {
    foreach (SearchResult result in results) {
        Console.WriteLine(result.Properties["cn"][0]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM