【问题标题】:Get the list of Groups for the given UserPrincipal获取给定 UserPrincipal 的组列表
【发布时间】:2012-04-20 10:15:44
【问题描述】:

我想获取用户所在的组列表。

这是我的代码:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.ac.uk",   "DC=mydomain,DC=AC,DC=UK", "user", "password");

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MyUser");

PrincipalSearchResult<Principal> results = user.GetGroups();

foreach(Principal p in results)
{
   Response.Write(p.Name);
}

运行时,Response.Write(p.Name); 行出现以下错误

System.Runtime.InteropServices.COMException: 指定的目录服务属性或值不存在。

当我检查结果计数时,它返回 9,第一组是DomainUsers

如何迭代列表中的所有 9 个组?谢谢。

以下是我得到的用户列表:

【问题讨论】:

  • 如何初始化 PrincipalContext?
  • PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.ac.uk", "DC=mydomain,DC=AC,DC=UK", "user", "password");
  • name 属性可能尚未填充(可能是因为它来自与您查询的域不同的域??)。尝试询问 DisplayName 或 DistinguishedName 或 SamAccountName 或 SID。
  • 我试过这些名字,但错误还是一样。当我在调试视图中检查时,以下是我得到的错误: Name ( '((System.DirectoryServices.AccountManagement.Principal)((new System.Linq.SystemCore_EnumerableDebugView(results)) .Items[1])).Name' 引发了类型为 'System.Runtime.InteropServices.COMException' 的异常)
  • 我猜这是因为您的“用户”帐户没有足够的权限来读取组对象。你看到DistinguishName 属性和Guid 属性了吗?

标签: c# active-directory userprincipal


【解决方案1】:

当省略 PrincipalContext 类中描述的 LDAP 容器属性时,运行代码的用户必须对默认的User 容器(即CN=Users,DC=yourDomain,DC=COM)和Computers 容器(即CN=Computers,DC=yourDomain,DC=COM)具有读取权限.

如果用户没有所需的权限,您将收到以下错误消息:

指定的目录服务属性或值不存在

  • ‘context.Container’引发了‘System.NullReferenceException’字符串类型的异常 {System.NullReferenceException}

  • ((新 System.Linq.SystemCore_EnumerableDebugView(groups)).Items[5]).Description' 抛出类型异常 ‘System.Runtime.InteropServices.COMException’ 字符串 {System.Runtime.InteropServices.COMException}

【讨论】:

  • 如果有人删除了相关域中的计算机容器,您也会收到此错误。看在上帝的份上...有人删除了这件事。
  • 任何人试图使用this.RequestContext.Principal.IsInRole("ad group name") 并且它总是返回 false 而没有抛出异常,这是一个可能的原因。恢复 CN 和权限为我解决了这个问题。
  • 博客的链接好像坏了。
【解决方案2】:

尝试类似的东西

foreach(Principal p in results)
{ 
   if (p is GroupPrincipal) 
      Response.Write(p.DisplayName); 
}

我知道这听起来很愚蠢,但它在过去对我有用。您的结果看起来实际上只找到了 1 个安全组和 8 个“其他”类型的组。那些“其他”组可能不具备这些属性。

【讨论】:

  • 对我来说,名字更好(DisplayName为空:user.GetGroups().OfType&lt;GroupPrincipal&gt;().Select(p =&gt; p.Name));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多