Friday, July 12, 2019

Get all Azure AD groups where current user is a member transitively via Graph API


As you probably know we may get all groups where user is member using memberOf endpoint:

GET /users/{id | userPrincipalName}/memberOf

This endpoint returns only those groups where user was added as direct member. I.e. if user was added to GroupA and this GroupA was then added to GroupB – it will return only GroupA but not GruopB. However we often need to get all groups where user is member transitively. Fortunately it is also possible with another endpoint getMemberGroups:

POST /users/{id | userPrincipalName}/getMemberGroups

Until recently it was available only in Graph API itself – not in .Net Graph client library. Fortunately starting with 1.16 version Microsoft.Graph.User class got new property TransitiveMemberOf propery:

Using this property we may get all groups where user is member transitively. It supports paging so in order to get all groups we also need to iterate through pages. Here is the code example which does that:

private static List<Guid> GetUserGroupsTrasitively(string userPrincipalName)
{
 try
 {
  var graph = new GraphServiceClient(new AzureAuthenticationProvider());
  var groups = graph.Users[userPrincipalName].TransitiveMemberOf.Request().GetAsync().Result;
  if (groups == null)
  {
   return new List<Guid>();
  }

  var result = new List<Guid>();
  while (groups.Count > 0)
  {
   foreach (var group in groups)
   {
    result.Add(new Guid(group.Id));
   }

   if (groups.NextPageRequest != null)
   {
    groups = groups.NextPageRequest.GetAsync().Result;
   }
   else
   {
    break;
   }
  }

  return result;
 }
 catch (Exception x)
 {
  // error handling
 }
}

No comments:

Post a Comment