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