检查用户是否属于同时属于Active Directory林中另一个组的组

时间:2014-02-26 15:01:55

标签: c# active-directory

我们有一个AD Forest,有两个不同的域。 假设我们有域A和域B.我们在域A中有一个“管理员”组。在该组中添加了来自域B的几个组。 如何检查用户是属于“管理员”组还是属于“管理员”组中的组?

我考虑的情景:

  1. 在域A中查找管理员组。
  2. 阅读属于“管理员”群组的所有群组和用户
  3. 查找当前UserPrincipal的所有组 可能是该主体属于域A和域B中的组。
  4. 将两个列表与各自的SID进行比较
  5. 将域A中的组对象的SID与添加(链接)到域B的同一组的SID进行比较是否安全? SID在一个森林方面总是独一无二的吗?

    更新 可以使用Ashigore提出的解决方案。 或者我写的解决方案:

    public IEnumerable<SecurityIdentifier> ReadAllMemebersForRecursive(string groupName)
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domainname", "user to access", "password");
                var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName);
    
                if (groupPrincipal == null)
                    return Enumerable.Empty<SecurityIdentifier>();
    
                return groupPrincipal.GetMembers(true).OfType<UserPrincipal>().Select(gp => gp.Sid);
          }
    
    
     IEnumerable<SecurityIdentifier> users = service.ReadAllMemebersForRecursive(groupName);
     var identity = WindowsIdentity.GetCurrent();
     var admin = users.Contains(identity.User);   
    

1 个答案:

答案 0 :(得分:3)

尝试使用System.DirectoryServices.AccountManagement命名空间:

static GroupPrincipal[] GetUserAuthorisationGroups(string userPrincipalName)
{
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.UserPrincipalName, userPrincipalName))
    {
        return user.GetAuthorizationGroups().OfType<GroupPrincipal>().ToArray();
    }
}

GetAuthorizationGroups将直接或由于嵌套组返回用户所属的所有安全组。然后你可以按照你想要的方式找到小组:

GroupPrincipal[] groups = GetUserAuthorisationGroups(szUPN);

bool searchBySid = groups.Any(g => g.Sid == groupSid);
bool searchByDN = groups.Any(g => g.DistinguishedName == groupDN);
bool searchByName = groups.Any(g => g.Name == groupName);
相关问题