Get the list of Groups for the given UserPrincipal

别来无恙 提交于 2019-11-27 06:47:29

问题


I want to get the list of groups which the user is in.

This is my code:

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);
}

When I run, I got the following error at the line Response.Write(p.Name);

System.Runtime.InteropServices.COMException: The specified directory service attribute or value does not exist.

When I checked the count of the results, it returned 9 and the first group is DomainUsers.

How can I iterate all 9 groups in the list? Thanks.

The following is the list of users I get:


回答1:


When omitting the LDAP container property as described in PrincipalContext Class, the user running the code must have read permissions to both the default User Container (i.e. CN=Users,DC=yourDomain,DC=COM) and the Computers Container (i.e. CN=Computers,DC=yourDomain,DC=COM).

If the user does not have the required permissions you will get the following error messages:

The specified directory service attribute or value does not exist

  • ‘context.Container’ threw an exception of type ‘System.NullReferenceException’ string {System.NullReferenceException}

  • ((new System.Linq.SystemCore_EnumerableDebugView(groups)).Items[5]).Description’ threw an exception of type ‘System.Runtime.InteropServices.COMException’ string {System.Runtime.InteropServices.COMException}




回答2:


try something like

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

I know it sounds dumb, but it has worked for me in the past. Your results look like it only actually found 1 security group and 8 "other" types of groups. Those "other" groups may not possess those attributes.



来源:https://stackoverflow.com/questions/10244297/get-the-list-of-groups-for-the-given-userprincipal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!