没有为active directory用户获取域用户组
本文关键字:获取 用户组 用户 directory active | 更新日期: 2023-09-27 18:29:38
我们使用以下代码来获取active directory用户的组。
StringCollection groups = new StringCollection();
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password))
{
//find user roles
UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginUserName);
if (user != null)
{
DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject();
object obGroups = de.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
groups.Add(obGpEntry.Name);
}
}
}
}
catch (Exception e)
{
}
这几乎和预期的一样有效。但是,当我们检查具有Domain Users
组的用户时,该方法没有返回组名。有些用户只使用这个Domain Users
组,当我们为这些用户调用此方法时,它返回一个空组。
有什么建议吗。。
这是一个众所周知的、有文档记录的"遗漏",即所谓的主组是而不是从该代码中的Groups
方法返回。有一些相当神秘的方法可以解决这个问题,或者尝试其他方法:
如果您使用的是.NET 3.5及更高版本,则应该检查System.DirectoryServices.AccountManagement
(S.DS-AM)命名空间。点击此处阅读:
- 在.NET Framework 3.5中管理目录安全主体
- System.DirectoryServices.AccountManagement上的MSDN文档
基本上,您可以定义域上下文,并在AD:中轻松找到用户和/或组
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// the call to .GetAuthorizationGroups() will return **all** groups that
// user is a member of - including the primary group and all nested
// group memberships, too!
var result = user.GetAuthorizationGroups();
}
新的S.DS.AM让在AD中与用户和组一起玩变得非常容易!
更新:如果您坚持使用旧的遗留技术,请查看Ryan Dunn的这篇博客文章,它详细解释了如何在C#中获得AD帐户的主要组。