Search code examples
c#microsoft-graph-apisharepoint-onlineonedrive

C# - Microsoft Graph - Can't access OneDrive/SharePoint site document library


I'm having issues accessing a sharepoint sites document library or even the users onedrive after authenticating to a registered graph api hosted in Azure AD. It seems like things are missing? I'm using the latest version of microsoft graph (5.6).

This code works:

using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Me.SendMail;
using Microsoft.Graph.Drives.Item.List.Items.Item.DriveItem;

namespace GraphApp
{
    class GraphHelper
    {
        //Settings object
        private static Settings? _settings;
        // User auth token credential
        private static DeviceCodeCredential? _deviceCodeCredential;
        // Client configured with user auth
        private static GraphServiceClient? _userClient;

        public static void InitializeGraphForUserAuth(Settings settings, Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
        {
            _settings = settings;

            var options = new DeviceCodeCredentialOptions
            {
                ClientId = settings.ClientId,
                TenantId = settings.TenantId,
                DeviceCodeCallback = deviceCodePrompt,
            };

            _deviceCodeCredential = new DeviceCodeCredential(options);
            _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
        }
        
        public static async Task<string> GetUserTokenAsync()
        {
            //Ensure cred isn't null
            _ = _deviceCodeCredential ??
                throw new System.NullReferenceException("Graph has not been initialized for auth");

            //Ensure scopes aren't null
            _ = _settings?.GraphUserScopes ?? throw new System.NullReferenceException("Arugment 'scopes' cannot be null");

            // Request token with given scopes
            var context = new TokenRequestContext(_settings.GraphUserScopes);
            var response = await _deviceCodeCredential.GetTokenAsync(context);
            return response.Token;
        }

        public static Task<User?> GetUserAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialzed for user auth");

            return _userClient.Me.GetAsync((config) =>
            {
                //Only request specific properties
                config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
            });
        }

MS Documentation states i should have a .Me.Drive.Root but absolutely nothing shows up here: My code for getting SharePoint Online drives.

enter image description here

Not sure what I'm doing wrong and I can't find any documentation

I've tried everything except posting HTTP get requests to graph which I want to avoid if possible

Entire code of graph helper:

using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Me.SendMail;
using Microsoft.Graph.Drives.Item.List.Items.Item.DriveItem;

namespace GraphApp
{
    class GraphHelper
    {
        //Settings object
        private static Settings? _settings;
        // User auth token credential
        private static DeviceCodeCredential? _deviceCodeCredential;
        // Client configured with user auth
        private static GraphServiceClient? _userClient;

        public static void InitializeGraphForUserAuth(Settings settings, Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
        {
            _settings = settings;

            var options = new DeviceCodeCredentialOptions
            {
                ClientId = settings.ClientId,
                TenantId = settings.TenantId,
                DeviceCodeCallback = deviceCodePrompt,
            };

            _deviceCodeCredential = new DeviceCodeCredential(options);
            _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
        }
        
        public static async Task<string> GetUserTokenAsync()
        {
            //Ensure cred isn't null
            _ = _deviceCodeCredential ??
                throw new System.NullReferenceException("Graph has not been initialized for auth");

            //Ensure scopes aren't null
            _ = _settings?.GraphUserScopes ?? throw new System.NullReferenceException("Arugment 'scopes' cannot be null");

            // Request token with given scopes
            var context = new TokenRequestContext(_settings.GraphUserScopes);
            var response = await _deviceCodeCredential.GetTokenAsync(context);
            return response.Token;
        }

        public static Task<User?> GetUserAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialzed for user auth");

            return _userClient.Me.GetAsync((config) =>
            {
                //Only request specific properties
                config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
            });
        }

        public static Task<MessageCollectionResponse?> GetInboxAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            return _userClient.Me
                //Only messages from Inbox
                .MailFolders["Inbox"]
                .Messages
                .GetAsync((config) =>
                {
                    //Only request specific properties
                    config.QueryParameters.Select = new[] { "from", "isRead", "receivedDateTime", "subject" };
                    // Get only top 25 results
                    config.QueryParameters.Top = 25;
                    //Sort by received time, newest first
                    config.QueryParameters.Orderby = new[] { "receivedDateTime DESC" };
                });
            
        }

        public static async Task SendMailAsync(string subject, string body, string recipient)
        {
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            //Create the message
            var message = new Message
            {
                Subject = subject,
                Body = new ItemBody
                {
                    Content = body,
                    ContentType = BodyType.Text
                },
                ToRecipients = new List<Recipient>
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = recipient
                        }
                    }
                }
            };

            //Send the message

            await _userClient.Me
                .SendMail
                .PostAsync(new SendMailPostRequestBody
                {
                    Message = message
                });
        }

        public static async Task GetSiteDetails(string sitename) //doesn't work
        {
            
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");
            
            var result = await _userClient.Sites.GetAsync((requestConfiguration) =>
            {
                requestConfiguration.QueryParameters.Search = $"{sitename}";
            });
        }

        public static async Task GetDrive()
        {
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            var childItems = _userClient.Me.Drive.
        }

    }
}

Solution

  • First you need to get your drive id

    var drive = await _userClient.Me.Drive.GetAsync(x=>
    {
        x.QueryParameters.Select = new string[] { "id" };
    });
    

    Then use the drive id to get the root item

    var rootItem = await _userClient.Drives[drive.Id].Root.GetAsync(x =>
    {
        x.QueryParameters.Select = new string[] { "id" };
    });
    

    Then use the drive id and the root id to get items in the root

    var response = await _userClient.Drives[drive.Id].Items[rootItem.Id].Children.GetAsync();
    var items = response.Value.ToList();
    

    For SharePoint site it's very similar

    Get site drive

    var siteDrive = await _userClient.Sites[siteId].Drive.GetAsync();
    

    Get site drive root item

    var siteDriveRootItem = await _userClient.Drives[siteDrive.Id].Root.GetAsync();
    

    Get items

    var response = await _userClient.Drives[siteDrive.Id].Items[siteDriveRootItem.Id].Children.GetAsync();
    var items = response.Value.ToList();