get group members from azure ad via microsoft graph

前端 未结 1 1208
無奈伤痛
無奈伤痛 2020-12-22 11:32

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 gra

相关标签:
1条回答
  • 2020-12-22 12:02

    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.

    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.

    Test Request Result:

    For more details you could refer to Official Document

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

    0 讨论(0)
提交回复
热议问题