我想要获取特定用户所属的所有 Active Directory 组。
我确实有脚本来获取用户的所有直接 AD 组(请参阅下面的代码)。
但是,如何获取用户所属的每个直接 AD 组的所有父组?
例如我是名为 IT 团队经理
的 AD 小组的直接成员。该组是名为 IT Team National
等父组的成员。如何从我的代码中获取该父组?
提前非常感谢!
DirectorySearcher ouSearch = new DirectorySearcher(entry);
ouSearch.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";
//ouSearch.PropertiesToLoad.Add("samAccountName");
ouSearch.PropertiesToLoad.Add("memberOf");
ouSearch.SearchScope = SearchScope.Subtree;
SearchResult allOUS = ouSearch.FindOne();
//foreach (string g in allOUS.Properties["memberOf"])
{
equalsIndex = g.IndexOf("=", 1);
commaIndex = g.IndexOf(",", 1);
if (equalsIndex == -1)
{
return null;
}
groupNames.Append(g.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append(",");
}
最佳答案
如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有相关内容:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
基本上,您可以定义域上下文并轻松在 AD 中查找用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// get the "authorization groups" the user is a member of - recursively
var authGroups = user.GetAuthorizationGroups();
// iterate over groups
foreach(Principal p in authGroups)
{
// do something with groups ....
}
}
新的 S.DS.AM 让 AD 中的用户和组的使用变得非常容易!
关于c# - 获取用户所属的所有父AD组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13024721/