Search code examples
sharepoint.net-coreazure-active-directorysharepoint-rest-apimicrosoft-graph-files

dotnet Core - Using azure AD authentication to retrive data from sharepoint REST API


My project is set up to use azure ad as login(from the dotnet core template). I have successfully managed to log in.

However, i want to use the same logged in user to retrive data from sharepoint rest api.

I have the following method:

public async Task<FileResults> Test()

    {
        var siteUrl = "https://xxxxx.sharepoint.com";

        var username = "[email protected]";
        var password = "xxxxxx";
        var securePassword = new SecureString();
        password.ToCharArray().ToList().ForEach(c => securePassword.AppendChar(c));
        var credentials = new SharePointOnlineCredentials(username, securePassword);

        var handler = new HttpClientHandler();
        handler.Credentials = credentials;

        var uri = new Uri(siteUrl);
        handler.CookieContainer.SetCookies(uri, credentials.GetAuthenticationCookie(uri));

        var json = string.Empty;
        using (var client = new HttpClient(handler))
        {
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
            var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/Delte%20dokumenter/Test')/Files");
            json = await response.Content.ReadAsStringAsync();

            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
            var files = result.FileResults;
            return files;
        }
    }

This is working fine and im getting documents from sharepoint. But, this is when using hardcoded credentials. How do i use the credentials of the logged in user via azure AD? Do i retrive the accesstoken?


Solution

  • To use the Azure AD Authentication you need to have one of the Authentication flows.

    Note: Username/Password flow is not recommended.

    After that you will be getting the tokens according to the scopes that are specified and you need to hit the Microsoft Graph Api, internally you need to hit the SharePoint API endpoints according to your requirement.

    You can start exploring with this sample