简体   繁体   中英

azure ad list users into combobox graph api C#

I'm currently working on an application where i need to get all the users from the company's azure ad

I manage to make a select and get all users into the ResultText textblock.

i now use the DisplayBasicTokenInfo() to fill a textbox but it only returns 1 username and that's my own. Now what i want to do is make a list of all the users and load these into a combobox via DisplayBasicTokenInfo.

I don't know if this is the best solution but it is what i found. The end goal for this is that i want every Displayname to be a comboboxItem

This is the code i have so far.

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

}

You use TokenInfoText.Text += $"{authResult.Account.Username}"; to set TokenInfoText in your case.

authResult.Account.Username just returned the signed-in user which used to get access token, but not the users the API returned.

If you just want to get all displayNames, you could decode the ResultText.Text and get the values. Convert JSON String to JSON Object c# .

Also you can use Microsoft Graph SDK to get the users.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM