azure ad list users into combobox graph api C#

azure ad list users into combobox graph api C#

我目前正在开发一个应用程序,我需要从公司的 azure 广告中获取所有用户

我设法制作了一个 select 并让所有用户进入 ResultText 文本块。

我现在使用 DisplayBasicTokenInfo() 来填充文本框,但它只有 returns 1 个用户名,那是我自己的。现在我想做的是列出所有用户并通过 DisplayBasicTokenInfo 将它们加载到组合框中。

我不知道这是否是最佳解决方案,但这是我找到的。最终目标是我希望每个 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 并获取值。 Convert JSON String to JSON Object c#.

您也可以使用 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;
}