WPF Application with Microsoft Graph API

As per my previous blog, we can easily integrate the Graph API in Windows Forms application.

In this article, I am going to select WPF application and connect with Graph API. The purpose of connecting with Graph API is that, it can provide a lot of information and intelligence. Apart from that, if you have Azure AD secured APIs, you can call those APIs using the authentication token. This will help to enable security in your application and service calls.

We are going to use the authentication with Azure AD v2 endpoint, which support authentication from consumer and commercial accounts using same code base. MSAL manages caching and refreshing access tokens for you, so that your application doesn’t need to.

Let’s build the sample step by step.

  1. In Visual Studio, select File > New > Project.Under Templates, select Visual C#.
  2. Select WPF App or WPF Application, depending on the version of Visual Studio version you’re using.
  3. Add MSAL to project by using Microsoft.Identity.Client nuget package including pre-release version.
  4. Adding Code to project –
  5. App.xaml.cs

    using Microsoft.Identity.Client;

    public partial class App : Application{

    private static string ClientId = “your_client_id_here”;

    public static PublicClientApplication PublicClientApp = new PublicClientApplication(ClientId);

    }

  6. MainWindow.xaml

  7. MainWindow.xaml.cs

    using Microsoft.Identity.Client;

    public partial class MainWindow : Window

    {

    string _graphAPIEndpoint = “https://graph.microsoft.com/v1.0/me“;

    string[] _scopes = new string[] { “user.read” };

    public MainWindow()

    {

    InitializeComponent();

    }

    private async void CallGraphButton_Click(object sender, RoutedEventArgs e)

    {

    AuthenticationResult authResult = null;

    try

    {

    authResult = await App.PublicClientApp.AcquireTokenSilentAsync(_scopes, App.PublicClientApp.Users.FirstOrDefault());

    }

    catch (MsalUiRequiredException ex)

    {

    System.Diagnostics.Debug.WriteLine($”MsalUiRequiredException: {ex.Message}”);

    try

    {

    authResult = await App.PublicClientApp.AcquireTokenAsync(_scopes);

    }

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

    this.SignOutButton.Visibility = Visibility.Visible;

    }

    }

    }

    public async Task 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);

    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();

    }

    }

    private void SignOutButton_Click(object sender, RoutedEventArgs e)

    {

    if (App.PublicClientApp.Users.Any())

    {

    try

    {

    App.PublicClientApp.Remove(App.PublicClientApp.Users.FirstOrDefault());

    this.ResultText.Text = “User has signed-out”;

    this.CallGraphButton.Visibility = Visibility.Visible;

    this.SignOutButton.Visibility = Visibility.Collapsed;

    }

    catch (MsalException ex)

    {

    ResultText.Text = $”Error signing-out user: {ex.Message}”;

    }

    }

    }

    private void DisplayBasicTokenInfo(AuthenticationResult authResult)

    {

    TokenInfoText.Text = “”;

    if (authResult != null)

    {

    TokenInfoText.Text += $”Name: {authResult.User.Name}” + Environment.NewLine;

    TokenInfoText.Text += $”Username: {authResult.User.DisplayableId}” + Environment.NewLine;

    TokenInfoText.Text += $”Token Expires: {authResult.ExpiresOn.ToLocalTime()}” + Environment.NewLine;

    TokenInfoText.Text += $”Access Token: {authResult.AccessToken}” + Environment.NewLine;

    }

    }

The authentication flow of this application is –

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s