簡體   English   中英

azure 廣告列表用戶進入 combobox 圖 api ZD7EFA19FBE7D3972FD4ADB6024223D7

[英]azure ad list users into combobox graph api C#

我目前正在開發一個應用程序,我需要從公司的 azure 廣告中獲取所有用戶

我設法制作了一個 select 並使所有用戶進入 ResultText 文本塊。

我現在使用 DisplayBasicTokenInfo() 來填充文本框,但它只返回 1 個用戶名,這是我自己的。 現在我要做的是列出所有用戶並通過 DisplayBasicTokenInfo 將這些用戶加載到 combobox 中。

我不知道這是否是最好的解決方案,但這是我發現的。 最終目標是我希望每個 Displayname 都是一個 comboboxItem

這是我到目前為止的代碼。

 public partial class TestGraphApi : Window
{
    //Set the API Endpoint to Graph 'users' endpoint
    string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/users?$select=displayName";

    //Set the scope for API call to user.read.all
    string[] _scopes = new string[] { "user.read.all" };

    public TestGraphApi()
    {
        InitializeComponent();
    }
    /// <summary>
    /// Call AcquireTokenAsync - to acquire a token requiring user to sign-in
    /// </summary>
    private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
    {
        AuthenticationResult authResult = null;
        var app = App.PublicClientApp;
        ResultText.Text = string.Empty;
        TokenInfoText.Text = string.Empty;

        var accounts = await app.GetAccountsAsync();
        var firstAccount = accounts.FirstOrDefault();

        try
        {
            authResult = await app.AcquireTokenSilent(_scopes, firstAccount)
                .ExecuteAsync();
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilent.
            // This indicates you need to call AcquireTokenInteractive to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                authResult = await app.AcquireTokenInteractive(_scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .WithPrompt(Prompt.SelectAccount)
                    .ExecuteAsync();
            }
            catch (MsalException msalex)
            {
                ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
            return;
        }

        if (authResult != null)
        {
            ResultText.Text = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);
            DisplayBasicTokenInfo(authResult);
        }
    }

    /// <summary>
    /// Perform an HTTP GET request to a URL using an HTTP Authorization header
    /// </summary>
    /// <param name="url">The URL</param>
    /// <param name="token">The token</param>
    /// <returns>String containing the results of the GET operation</returns>
    public async Task<string> GetHttpContentWithToken(string url, string token)
    {
        var httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpResponseMessage response;
        try
        {
            var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            //Add the token in Authorization header
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            response = await httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

    /// <summary>
    /// Display basic information contained in the token
    /// </summary>
    private void DisplayBasicTokenInfo(AuthenticationResult authResult)
    {
        TokenInfoText.Text = "";
        if (authResult != null)
        {
            TokenInfoText.Text += $"{authResult.Account.Username}";
        }
    }

}

您使用TokenInfoText.Text += $"{authResult.Account.Username}"; 在您的情況下設置 TokenInfoText 。

authResult.Account.Username只是返回了用於獲取訪問令牌的登錄用戶,而不是 API 返回的用戶。

如果您只想獲取所有顯示名稱,您可以解碼ResultText.Text並獲取值。 將 JSON 字符串轉換為 JSON Object Z240AA2CEC4B29C56F3BEE520A8DCEE7

您也可以使用Microsoft Graph SDK來獲取用戶。

private async Task<List<User>> GetUsersFromGraph()
{
    // Create Graph Service Client, refer to https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth
    IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithRedirectUri(redirectUri)
            .WithClientSecret(clientSecret) 
            .Build();

    AuthorizationCodeProvider authenticationProvider = new AuthorizationCodeProvider(confidentialClientApplication, scopes);

    GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);

    // Create a bucket to hold the users
    List<User> users = new List<User>();

    // Get the first page
    IGraphServiceUsersCollectionPage usersPage = await graphServiceClient
        .Users
        .Request()
        .Select(u => new {
            u.DisplayName
        })
        .GetAsync();

    // Add the first page of results to the user list
    users.AddRange(usersPage.CurrentPage);

    // Fetch each page and add those results to the list
    while (usersPage.NextPageRequest != null)
    {
        usersPage = await usersPage.NextPageRequest.GetAsync();
        users.AddRange(usersPage.CurrentPage);
    }

    return users;
}

暫無
暫無

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

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