簡體   English   中英

MS Graph Api 未返回所有用戶信息,例如手機、辦公電話

[英]MS Graph Api is not returning all user information such as mobile phones ,office phones

我正在使用下面的代碼來獲取所有用戶信息,例如 DisplayName 、Office 、Manager name 、Office Phones 等。

但是對於少數用戶,它不返回手機和辦公電話信息。

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;

namespace MSGraphAPI
{
    class Program
    {


        private static string clientId = "XXXXXXXXXX";


        private static string tenantID = "XXXXX";


        private static string objectId = "XXXXX";


        private static string clientSecret = "XXXX";

        static async System.Threading.Tasks.Task Main(string[] args)
        {




            //     IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            //.Create(clientId)
            //.WithTenantId(tenantID)
            //.WithClientSecret(clientSecret)
            //.Build();

            //        ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            //        GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            //        var users = await graphClient.Users
            //            .Request()
            //            .GetAsync();

            int Flag = 0;
            var tenantId = "XXXXX.onmicrosoft.com";

            // The client ID of the app registered in Azure AD
            var clientId = "XXXX";

            // *Never* include client secrets in source code!
            var clientSecret = "XXXXX"; // Or some other secure place.

            // The app registration should be configured to require access to permissions
            // sufficient for the Microsoft Graph API calls the app will be making, and
            // those permissions should be granted by a tenant administrator.
             var scopes = new string[] { "https://graph.microsoft.com/.default" };


            // Configure the MSAL client as a confidential client
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithAuthority($"https://login.microsoftonline.com/XXXX.onmicrosoft.com/v2.0")
                .WithClientSecret(clientSecret)
                .Build();

            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request. 
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) => {

        // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
        var authResult = await confidentialClient
            .AcquireTokenForClient(scopes)
            .ExecuteAsync();

        // Add the access token in the Authorization header of the API request.
        requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
                })
                );

            // Make a Microsoft Graph API query
            var users = await graphServiceClient.Users.Request().GetAsync();


            // var groups = await graphServiceClient.Groups.Request().GetAsync();

            //   IGraphServiceUsersCollectionPage userss = await graphServiceClient.Users.Request().GetAsync();




            do
            {
                        foreach (User user in users)
                        {




                            Console.WriteLine(user.DisplayName);
                            Console.WriteLine(user.BusinessPhones);
                            Console.WriteLine(user.MobilePhone);



                           // Console.WriteLine($"{user.Id}");
                            Flag++;
                        }
                    }
                    while (users.NextPageRequest != null && (users = await users.NextPageRequest.GetAsync()).Count > 0);

                    Console.WriteLine("------");


            Console.WriteLine(Flag);
        }
    }
}

我嘗試過以下范圍:

var scopes = new string[] { " https://graph.microsoft.com/User.ReadWrite.All "};

但是,這會引發異常:

MsalServiceException:AADSTS70011:提供的請求必須包含“范圍”輸入參數。 為輸入參數“范圍”提供的值無效。 范圍https://graph.microsoft.com/User.ReadWrite.All無效。 跟蹤 ID:XXXX-c578-42af-8bd2-7ddd54ee9201

我在 Azure Active Directory 門戶中交叉檢查,所有用戶都配置了商務電話和移動電話。 請幫忙。

首先,您的scope減速不正確。 Microsoft Graph不支持多scope分配,因為您嘗試分配為格式不正確的字符串列表。 另外不是scopes ,它將是scope

C#字符串數組中通常聲明為List<string>

您可以嘗試按照預期正常工作的代碼片段。

    //Token Request End Point
    string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/v2.0/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-a695-4aea-ad87-e6921e61f659",
        ["client_secret"] = "Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=",
        ["scope"] = "https://graph.microsoft.com/.default" 
    });

    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 Data from Microsoft Graph Rest API
    HttpClient _client = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/users"));
    //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());

使用的類:

 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; }
    }

我收到了這個回復 請看下面的截圖:

在此處輸入圖片說明

希望這會幫助你。

Microsoft Graph API 以分頁格式返回用戶,因此要獲取下一個用戶列表,您必須查詢當前響應的@odata.nextLink中提到的 url,這將為您提供下一組用戶。

為此,您可以運行 for 循環,直到@odata.nextLink返回NULL值為止。

更新:

  1. 查詢圖形 api 以獲取用戶獲取用戶

  2. 使用“@odata.nextLink”查詢圖形 API 以獲取下一組用戶。 使用 nextLink 獲取用戶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM