【问题标题】:Get Primary Group From UserPrincipal C#从 UserPrincipal C# 获取主组
【发布时间】:2019-07-11 16:58:34
【问题描述】:

我想从下面的代码中找到主要组

我可以获得一个用户的所有组,但哪个是主要组?

        string primaryGroupName = String.Empty;
        using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
        {
            using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "userName"))
            {
                foreach (Principal p in user.GetGroups())
                {
                    WriteLog("PrimaryGroup Name(s)???:");
                    WriteLog(p.Name);
                    primaryGroupName = p.Name;
                }
            }
        }

上面的代码返回的是……

域用户
管理员
架构管理员
企业管理员
域管理员
..还有更多

什么是主要组?

【问题讨论】:

  • 您可以获取主要组 id,但我不知道如何从那里获得组的名称。 var userEntry = user.GetUnderlyingObject() as DirectoryEntry; var primaryGroupId = userEntry.Properties["primaryGroupID"].Value;
  • @Amy 谢谢,这似乎给了我一个 id(即 513)现在我如何使用 id 来获取组名?
  • 我说我不知道​​该怎么做,对不起。
  • SID 的最后一个数字是否可能是“id”? sid=S-1-5-21-xxxxxxxxxx-xxxxxxxxx-xxxxxxxxx-513

标签: c# active-directory principalcontext


【解决方案1】:

您有正确的想法:primaryGroupID 保存作为主要组的组的 RID(相对标识符)。 RID 是 SID 中的最后一组数字。 SID 的其余部分标识域。因此,您可以使用用户的 SID 和 primaryGroupID 找出组的 SID。

我为此写了几篇文章。一个名为What makes a member a member?,其中有一节描述了主要组。还有一篇名为Finding all of a user’s groups 的文章,我在其中分享了一些代码来查找主要组。我发现直接使用DirectoryEntry总是比使用UserPrincipal/GroupPrincipal 快,所以这就是我的示例使用的:

方法如下:

private static string GetUserPrimaryGroup(DirectoryEntry de) {
    de.RefreshCache(new[] {"primaryGroupID", "objectSid"});

    //Get the user's SID as a string
    var sid = new SecurityIdentifier((byte[])de.Properties["objectSid"].Value, 0).ToString();

    //Replace the RID portion of the user's SID with the primaryGroupId
    //so we're left with the group's SID
    sid = sid.Remove(sid.LastIndexOf("-", StringComparison.Ordinal) + 1);
    sid = sid + de.Properties["primaryGroupId"].Value;

    //Find the group by its SID
    var group = new DirectoryEntry($"LDAP://<SID={sid}>");
    group.RefreshCache(new [] {"cn"});

    return group.Properties["cn"].Value as string;
}

要从您的代码中使用它,您可以这样做:

var primaryGroupName = GetUserPrimaryGroup((DirectoryEntry) user.GetUnderlyingObject());

该方法只返回组的名称,但您可以根据需要对其进行修改。

话虽如此,513 始终是内置域用户组的 RID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多