1

I am trying to retrieve a list of users from an azure security group, however i am having trouble with this, as i do not know the best possible and easy way to do this in c#. Any help/direction and sample code would be grateful.

2 Answers2

1

To retrieve list of users from an azure security group, make sure to grant the below API permission:

enter image description here

Please try using the below script by Jason Pan in this SO Thread like below:

 public async Task<JsonResult> sample()
    {
        var clientId = Your_Client_ID;
        var clientSecret = Your_Client_Secret;
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var tenantId = Your_Tenant_ID;
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };
            var clientSecretCredential = new ClientSecretCredential(
            tenantId, clientId, clientSecret, options);
            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
        try
        {
            var members = await graphClient.Groups["Your_Group_ID"].Members.Request().GetAsync();
            return Json(members);
        }
        catch (Exception e)
        {
            return Json("");
            throw;
        }
    }
Rukmini
  • 6,015
  • 2
  • 4
  • 14
0

You can use Microsoft Graph restful web APIs to access microsoft cloud resources . It has api endpoints for groups , users etc. In your case you can use list groups endpoint to fetch the groups.

https://learn.microsoft.com/en-us/graph/api/resources/group?view=graph-rest-1.0

simmyk
  • 26
  • 4
  • how do i authenticate first? what should i supply in the request body? – user19329953 Jul 19 '22 at 12:02
  • For postman [link]https://learn.microsoft.com/en-us/graph/use-postman?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 this will help ... For code what you need is create a GraphServiceClient and use same . This client would need same ClientId and Secret as mentioned in bove link – simmyk Jul 19 '22 at 12:14
  • in C#, namespace needed using Microsoft.Graph; using Microsoft.Graph.Auth; and you can register client like below :- services.AddSingleton(provider => new GraphServiceClient(new ClientCredentialProvider(ConfidentialClientApplicationBuilder .Create("AppClientId") .WithTenantId("TenantId") .WithClientSecret("AppClientSecret") – simmyk Jul 19 '22 at 12:40
  • I'm using the code above and making use of the Microsoft.Graph namespace - however it keeps saying that an error has occurred while sending request. I'm not sure why i have checked the credentials and also set up permissions for the api on azure end,... – user19329953 Jul 19 '22 at 13:13
  • Can you try via postman if your credentials are working or not? – simmyk Jul 20 '22 at 06:11