How can I access SharePoint files via a C# web api that uses no user authentication?

David Finkelstein 0 Reputation points
2024-04-26T17:41:06.5666667+00:00

I have followed numerous guides on how to access SharePoint via C# and no matter what I do I end up with a "401 Unauthorized response:" I am out o fideas. Anybody able to help? Would prefer working code examples.

using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;

namespace SharePointRestApiExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string siteUrl = "https://mydomain.sharepoint.com/sites/mysite";
            string clientId = "client id from app registration";
            string clientSecret = "client secret from app registration";
            string tenantId = "tenant id from my instance";
            string authority = $"https://login.microsoftonline.com/tenant id from my instance";
            string[] scopes = new string[] { "https://mydomain.sharepoint.com/.default" };
            string folderUrl = "/sites/mysite";
			var cca = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri(authority))
            .WithRedirectUri("https://localhost")
            .Build();
	        try
    	    {
            var authResult = await cca.AcquireTokenForClient(scopes).ExecuteAsync();
            string accessToken = authResult.AccessToken;
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await httpClient.GetAsync($"{siteUrl}/_api/web?select=Title");
                if (!response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"Failed to retrieve site info: {response.StatusCode}. Server response: {responseContent}");
                 }
                else
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    JObject json = JObject.Parse(jsonResponse);
                    string title = json["d"]["Title"].ToString();
                    Console.WriteLine($"Site Title: {title}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,154 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,575 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
315 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 33,251 Reputation points Microsoft Vendor
    2024-04-29T03:09:58.7266667+00:00

    Hi @David Finkelstein,

    To use the REST capabilities that are built into SharePoint, you construct a RESTful HTTP request by using the OData standard, which corresponds to the client object model API you want to use. The client.svc web service handles the HTTP request and serves the appropriate response in either Atom or JSON format. The client application must then parse that response. Please refer to following document

    https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-rest-endpoints#reading-data-with-the-sharepoint-rest-interface


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.