0
votes

I am working in asp.net application Authenticate with external identity provider (Azure Active Directory)

I want to get group members from azure ad via microsoft graph

How can I do that ??

1
Can you please tell us what you've tried, and where you are stuck? This will also help us answer your question better.Philippe Signoret

1 Answers

2
votes

Seems You are trying to get all group members from a specific group. Just Get the group Id that is Object Id on azure portal. See the below screen shot.

enter image description here

Code Snippet :

You could try following code snippet which work fine as expected.

    //Token Request End Point
    string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/token";
    var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

    //I am Using client_credentials as It is mostly recommended
    tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["grant_type"] = "client_credentials",
        ["client_id"] = "b6695c7be_YourClient_Id_e6921e61f659",
        ["client_secret"] = "Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=",
        ["resource"] = "https://graph.microsoft.com/" 
    });

    dynamic json;
    AccessTokenClass results = new AccessTokenClass();
    HttpClient client = new HttpClient();

    var tokenResponse = await client.SendAsync(tokenRequest);

    json = await tokenResponse.Content.ReadAsStringAsync();
    results = JsonConvert.DeserializeObject<AccessTokenClass>(json);


    //New Block For Accessing Group Member List from Microsoft Graph Rest API
    var groupId = "Group Id which Member You want to Retrieve";
    HttpClient _client = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/groups/{0}/members"),groupId);
    //Passing Token For this Request
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
    HttpResponseMessage response = await _client.SendAsync(request);
    //Get User List With Business Phones and Mobile Phones
    dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

Class Used:

 public class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
    }

Permission:

You need to set User.Read.All, Group.Read.All, Directory.Read.All Application permission on Microsoft Graph API on azure portal.

enter image description here

Test Request Result:

enter image description here

For more details you could refer to Official Document

Hope it would help. Feel free to share if you encounter any problem.