Reputation: 7306
In my Active Directory (my.domain), I have many groups (UserGrp1, UserGrp2, etc.) which have many users. A user can exist in more than one group. I currently have code that allows me to use the GroupPrincipal class to find a group, and then from there to get all members of that group (see code below). However, what I really need is to find all groups to which a user belongs. For instance, I have a domain user named Joe Test (sAMAccountName=JOETEST) and I need to find all groups to which he belongs. What is the best way to do this?
I can determine if a user belongs to a group (as below) if I loop through all members returned by the GetMembers() method, but this seems inefficient to me and I'd be surprised were there not 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 that I receive on this.
Upvotes: 2
Views: 5029
Reputation: 7892
Do it by using UserPrincipal.GetGroups();
For a complete code here it is
/// <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 a full AD reference go here.
Upvotes: 4