Azure ADMS Graph

Working with OneDrive data and MS Graph in .NET Core

Learn how to interact with your OneDrive data via the GraphAPI, Azure AD and .NET Core. In this blog post I explain how to use .NET Core and the Graph API with the latest MSAL library to authenticate a user and then provide access to the OneDrive data. Full code sample also available on GitHub

Working with OneDrive data and MS Graph in .NET Core

It's been a very long time since I tried to access my OneDrive data programmatically and I was curious to find out what the new experience is like. Especially since MS Graph now allows you to interact with your OneDrive data programmatically using .NET Core. The nice thing is that I didn't have to start from scratch and I was able to get the project off the ground quickly using one of the existing MS Graph tutorials. The code for this project is loosely based on this .NET Core sample. And it took a little bit of experimentation and looking up the Graph API documentation to find out how to make calls to my OneDrive via the MS Graph Files API.

But before we even touch the code, we can get a feel of what it looks like to work with the Graph API for OneDrive via the Graph Explorer - I truly love this tool as it allows me to get a quick glance into the possibilities of MS Graph.

Now that I have  a good grasp of what I can do with with MS Graph, I'm ready to start playing with the code. For this project, we have the following components:

  • .NET Core 3.1
  • Visual Studio Code
  • MSAL (Microsoft Authentication Library)
  • Graph SD

And since I'm using a console app, I am going with Device Code Flow for the authentication. The device code flow is a type of authentication flow that is designed for native applications (desktop, mobile…) which are by nature considered “insecure” (in the sense that you do not have direct control over the execution context).

Create the .NET console app

Open the command prompt of choice and type the following to create the console app and add the appropriate dependencies/NuGet packages:

mkdir OneDriveWithMsGraph
cd OneDriveWithMSGraph
dotnet new console

dotnet add package Microsoft.Extensions.Configuration.UserSecrets --version 3.1.2
dotnet add package Microsoft.Identity.Client --version 4.10.0
dotnet add package Microsoft.Graph --version 3.0.1

We now have a basic .NET Console app. The packages above add MS Graph and MSAL libraries as well as a standard .NET Core config extension where we can store user secrets such as API Keys etc that can be used during development. Although this is a bit of an overkill and for this exercise we don't have any sensitive information to store, it's a really good practice to follow :)

Register your Azure AD app

Next, we need to create an App registration in Azure Active Directory to allow our users to interact with their OneDrive data. For this scenario, I opted for a single-tenant, line of business (LOB) app assuming that we only want to give access to our corporate OneDrive data. It's a subtle configuration change in the AAD App with significant connotations. If you opt in for another registration model, the app can also allow be used to access personal OneDrive data using Microsoft Account.

To register a new application, head over to the Azure AD blade in the Azure Portal.

Ensure to set the Redirect URI to https://login.microsoftonline.com/common/oauth2/nativeclient. Next, navigate to the Authentication tab and set the Default Client Type option to Yes under Advanced Settings

Go back to the Overview and grab both the Application ID and Tenant ID values as we will need them in our app. Our Azure AD configuration is complete

Implement the Authentication code

Back in our .NET console app let's add the AppId to our our local secrets. Open the console and type the following:

dotnet user-secrets init
dotnet user-secrets set appId "YOUR_APP_ID_HERE"
dotnet user-secrets set scopes "User.Read;Files.ReadWriteAll;Files.ReadWriteAppFolder"

We also need to create a new class named DeviceCodeAuthProvider and add the following code to perform the authentication:

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace OneDriveWithMSGraph
{
    public class DeviceCodeAuthProvider : IAuthenticationProvider
    {
        private IPublicClientApplication _msalClient;
        private string[] _scopes;
        private IAccount _userAccount;

        public DeviceCodeAuthProvider(string appId, string[] scopes)
        {
            _scopes = scopes;

            _msalClient = PublicClientApplicationBuilder
                .Create(appId)
                .WithAuthority(AadAuthorityAudience.AzureAdMyOrg, true)
                .WithTenantId("b55f0c51-61a7-45c3-84df-33569b247796")
                .Build();
        }

        public async Task<string> GetAccessToken()
        {
            // If there is no saved user account, the user must sign-in
            if (_userAccount == null)
            {
                try
                {
                    // Invoke device code flow so user can sign-in with a browser
                    var result = await _msalClient.AcquireTokenWithDeviceCode(_scopes, callback => {
                        Console.WriteLine(callback.Message);
                        return Task.FromResult(0);
                    }).ExecuteAsync();

                    _userAccount = result.Account;
                    return result.AccessToken;
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"Error getting access token: {exception.Message}");
                    return null;
                }
            }
            else
            {
                // If there is an account, call AcquireTokenSilent
                // By doing this, MSAL will refresh the token automatically if
                // it is expired. Otherwise it returns the cached token.

                    var result = await _msalClient
                        .AcquireTokenSilent(_scopes, _userAccount)
                        .ExecuteAsync();

                    return result.AccessToken;
            }
        }

        // This is the required function to implement IAuthenticationProvider
        // The Graph SDK will call this function each time it makes a Graph
        // call.
        public async Task AuthenticateRequestAsync(HttpRequestMessage requestMessage)
        {
            requestMessage.Headers.Authorization =
                new AuthenticationHeaderValue("bearer", await GetAccessToken());
        }
    }
}

View DeviceCodeAuthProvider.cs on GitHub

The difference here, when compared to the sample I based my code on, is that I'm explicitly configuring the my app to work with TenantId using the .WithAuthority(AadAuthorityAudience.AzureAdMyOrg, true) and .WithTenantId(<YourTenantId>) as per the complete code below:

    _msalClient = PublicClientApplicationBuilder
                .Create(appId)
                .WithAuthority(AadAuthorityAudience.AzureAdMyOrg, true)
                .WithTenantId("<YourTenantId>")
                .Build();

Add the Graph API calls

Next, we need to should add a GraphHelper.cs class to do the necessary MS Graph calls. Notably, we have 3 main methods:

  • GetMeAsync()
  • GetOneDriveAsync()
  • GetDriveContentsAsync()
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace OneDriveWithMSGraph
{
    public class GraphHelper
    {
        private static GraphServiceClient graphClient;
        public static void Initialize(IAuthenticationProvider authProvider)
        {
            graphClient = new GraphServiceClient(authProvider);
            graphClient.BaseUrl = "https://graph.microsoft.com/beta";
        }

        public static async Task<User> GetMeAsync()
        {
            try
            {
                // GET /me
                return await graphClient.Me.Request().GetAsync();
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting signed-in user: {ex.Message}");
                return null;
            }
        }

        public static async Task<Drive> GetOneDriveAsync()
        {
            try
            {
                // GET /me
                return await graphClient.Me.Drive.Request().GetAsync();
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting OneDrive data: {ex.Message}");
                return null;
            }
        }

        public static async Task<IEnumerable<DriveItem>> GetDriveContentsAsync()
        {
            try
            {
                return await graphClient.Me.Drive.Root.Children.Request().GetAsync();
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting One Drive contents: {ex.Message}");
                return null;
            }
        }
    }
}

View GraphHelper.cs on GitHub

Make it all work - OneDrive with MS Graph

The last step is to implement the code that calls our helpers and pulls the OneDrive data we need. Open the Program.cs file and paste the following code:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;

namespace OneDriveWithMSGraph
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Working with Graph and One Drive is fun!");

            var appConfig = LoadAppSettings();

            if (appConfig == null)
            {
                Console.WriteLine("Missing or invalid appsettings.json...exiting");
                return;
            }

            var appId = appConfig["appId"];
            var scopesString = appConfig["scopes"];
            var scopes = scopesString.Split(';');

            // Initialize the auth provider with values from appsettings.json
            var authProvider = new DeviceCodeAuthProvider(appId, scopes);

            // Request a token to sign in the user
            var accessToken = authProvider.GetAccessToken().Result;
            GraphHelper.Initialize(authProvider);

            int choice = -1;
            while (choice != 0)
            {
                Console.WriteLine("Please choose one of the following options:");
                Console.WriteLine("0. Exit");
                Console.WriteLine("1. Display your access token");
                Console.WriteLine("2. Get your OneDrive root folder");
                Console.WriteLine("3. List your OneDrive contents");
                try
                {
                    choice = int.Parse(Console.ReadLine());
                }
                catch (System.FormatException)
                {
                    // Set to invalid value
                    choice = -1;
                }

                switch (choice)
                {
                    case 0:
                        // Exit the program
                        Console.WriteLine("Goodbye...");
                        break;
                    case 1:
                        // Display access token
                        Console.WriteLine($"The access token is:{accessToken}");
                        break;
                    case 2:
                        // Get OneDrive Info
                        Console.WriteLine(string.Empty);
                        Console.ForegroundColor = ConsoleColor.Green;
                        var driveInfo = await GraphHelper.GetOneDrive();
                        Console.WriteLine(FormatDriveInfo(driveInfo));
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                    case 3:
                        // Get OneDrive contents
                        var driveContents = await GraphHelper.GetDriveContents();
                        Console.WriteLine(string.Empty);
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(ListOneDriveContents(driveContents.ToList()));
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    default:
                        Console.WriteLine("Invalid choice! Please try again.");
                        break;
                }
            }
        }

        static IConfigurationRoot LoadAppSettings()
        {
            var appConfig = new ConfigurationBuilder()
                .AddUserSecrets<Program>()
                .Build();

            if (string.IsNullOrEmpty(appConfig["appId"]) ||
                string.IsNullOrEmpty(appConfig["scopes"]))
            {
                return null;
            }

            return appConfig;
        }

        static string FormatDriveInfo(Drive drive)
        {
            var str = new StringBuilder();
            str.AppendLine($"The OneDrive Name is: {drive.Name}");
            str.AppendLine($"The OneDrive Ownder is: {drive.Owner.User.DisplayName}");
            str.AppendLine($"The OneDrive id is: {drive.Id}");
            str.AppendLine($"The OneDrive was modified last by: {drive?.LastModifiedBy?.User?.DisplayName}");

            return str.ToString();
        }

        static string ListOneDriveContents(List<DriveItem> contents)
        {
            if (contents == null || contents.Count == 0)
            {
                return "No content found";
            }

            var str = new StringBuilder();
            foreach (var item in contents)
            {
                if (item.Folder != null)
                {
                    str.AppendLine($"'{item.Name}' is a folder");
                }
                else if (item.File != null)
                { 
                        str.AppendLine($"'{item.Name}' is a file with size {item.Size}");
                }
                else if (item.Audio != null)
                {
                    str.AppendLine($"'{item.Audio.Title}' is an audio file with size {item.Size}");
                }
                else
                {
                    str.AppendLine($"Generic drive item found with name {item.Name}");
                }            
            }

            return str.ToString();
        }
    }
}

View GraphCallsInMain.cs on GitHub

The code above:

  • Creates an appconfig and pulls our secrets in
  • Initializes the authentication provider helper class
  • Passes the auth provider to the GraphClient
  • Provides an interactive way for the user to pull the data in the console app

If you run the code the first time and select option "1" you are presented with your Authentication Token.  

You can grab your authentication token and use the jwt.ms website to inspect it like in the example below (always handy if you want to ensure that your jwt tokens are in order:

Running the app and selecting option 2 or option 3 returns the following results respectively:

Fairly basic functionality so far but with all this in place, we are now able to start adding, removing editing files and folders in our OneDrive. In effect, we can programmatically do whatever the UI offers and more!

As always, you can find a fully working code sample on GitHub.

Summary

I was pleasantly suprised to see that MS Graph and MSAL have transfored the way we programmatically interact with not just OneDrive but all our Office365 data. The next time you are creating an app for your enterprise, think about how you can delight your users and create richer, more immersive experiences by leveraging the power of MS Graph and MSAL. Let me know what you think and feel free to reach out if you have any questions :)