User search through GroupPrincipal

In my Active Directory (my.domain) I have many groups (UserGrp1, UserGrp2, etc.) in which there are many users. A user can exist in several groups. I currently have code that allows me to use the GroupPrincipal class to search for a group, and then from there to get all the members of this group (see code below). However, I really need to find all the groups the user belongs to. For example, I have a domain user named Joe Test (sAMAccountName = JOETEST), and I need to find all the groups to which it belongs. What is the best way to do this?

I can determine if the user belongs to a group (as shown below) if I go through all the members returned by the GetMembers () method, but this seems ineffective to me and I would be surprised if there wasn’t a more efficient way.

using (PrincipalContext ctx = new PrincipalContext( ContextType.Domain, "my.domain", "DC=my,DC=domain")) { if (ctx != null) { using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, "UserGrp1")) { // Get all group members PrincipalSearchResult<Principal> psr = gp.GetMembers(); foreach (Principal p in psr) { // other logic } } } } 

Thanks in advance for any help I get from this.

+1
source share
1 answer

Do this using UserPrincipal.GetGroups();

For the full code here

 /// <summary> /// Gets a list of the users group memberships /// </summary> /// <param name="sUserName">The user you want to get the group memberships</param> /// <returns>Returns an arraylist of group memberships</returns> public ArrayList GetUserGroups(string sUserName) { ArrayList myItems = new ArrayList(); UserPrincipal oUserPrincipal = GetUser(sUserName); PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups(); foreach (Principal oResult in oPrincipalSearchResult) { myItems.Add(oResult.Name); } return myItems; } /// <summary> /// Gets a certain user on Active Directory /// </summary> /// <param name="sUserName">The username to get</param> /// <returns>Returns the UserPrincipal Object</returns> public UserPrincipal GetUser(string sUserName) { PrincipalContext oPrincipalContext = GetPrincipalContext(); UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName); return oUserPrincipal; } /// <summary> /// Gets the base principal context /// </summary> /// <returns>Retruns the PrincipalContext object</returns> public PrincipalContext GetPrincipalContext() { PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword); return oPrincipalContext; } 

or for the full AD link go here .

+3
source

Source: https://habr.com/ru/post/887976/


All Articles