'Active directory check if user belongs to a group

I am using the below code to pull active directory groups. How can I find out if a user belongs to xyz group or not?

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a GroupPrincipal 
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}


Solution 1:[1]

You can get the list of groups a user is a member of by querying the memberOf navigation property on the user object.

Read about it here.

https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?api-version

Note that you can remove the $links part of the query to return the whole group object, rather than the link to the object. However, for simply validating a user is a member of a certain group, you can use the links, and compare the object id of the groups that are returned to the one you are looking for.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shawn Tabrizi