Home > Enterprise >  How to retrieve all the groups that a user has from Azure AD in C# ASP.NET Core 6.0?
How to retrieve all the groups that a user has from Azure AD in C# ASP.NET Core 6.0?

Time:12-07

I'm trying to get all the groups that an user has but I can't achieve that. Here's what I've been trying:

public async Task<string> traerGrupos(string userID)
{
            string currentUser = "null";

            try
            {
                var tenant = "mytenant";
                var clientID = "myclientid";
                var secret = "mysecretkey";
                var clientSecretCred = new ClientSecretCredential(tenant, clientID, secret);
                
                GraphServiceClient graphClient = new GraphServiceClient(clientSecretCred);

                var usr = graphClient.Users[userID.ToString()].Request()
                .Select(x => x.DisplayName).GetAsync().Result;

                currentUser = usr.DisplayName;
                return currentUser;
            }
            catch (Exception ex)
            {
                return currentUser = ex.Message;
            }
}

But I cannot see an option to get the groups. Besides, I get this error:

Code: Authorization_RequestDenied Message: Insufficient privileges to complete the operation.
Inner error: AdditionalData: date: 2022-12-06T19:54:23...

but my app has every permission that it requires.

How could I solve this? Thank you very much!

CodePudding user response:

If you have the scope set up correctly in the app registration, try to add the scope in your GraphServiceClient constructor,

string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

GraphServiceClient graphClient = new GraphServiceClient(clientSecretCred, scope);

CodePudding user response:

Given that you have the correct credentials/rights for the graph API as Charles Han says.

Remember that you can try the explorer the Graph API and read more in the docs about transitiveMemberOf

I would do/have done something like this

...
//{userPrincipalName} = email or id {GUID} of user
 var usersTentativeGroups = new List<ADTentativeGroup>();

            await SetAccessTokenInHeader();
            var url = $"https://graph.microsoft.com/v1.0/users/{userPrincipalName}/transitiveMemberOf";
            var jsonResp = await _client.GetAsync(url);

            var result = JsonConvert.DeserializeObject<ADGroupRoot>(await jsonResp.Content.ReadAsStringAsync());
            AddResultIfNotNull(usersTentativeGroups, result);

            while (!string.IsNullOrEmpty(result?.NextLink))
            {
                await SetAccessTokenInHeader();
                jsonResp = await _client.GetAsync(result.NextLink);
                result = JsonConvert.DeserializeObject<ADGroupRoot>(await jsonResp.Content.ReadAsStringAsync());
                AddResultIfNotNull(usersTentativeGroups, result);
            }
  • Related