SharePoint Online 401 Error.
Hello,
I am trying to use the Microsoft.SharePoint.Client (CSOM) API in a C# application, but I keep receiving a 401 Unauthorized error.
Within Azure, I created an App Registration and a secret key with the following API permissions:
I registered the app within SharePoint using the URL: https://*****admin.sharepoint.com/_layouts/15/AppRegNew.aspx.
After registration, I configured the app with the permission XML and selected the "Trust It" option.
Here is the permission XML I used:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="https://****.sharepoint.com/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>
Despite ensuring all IDs and secrets are correct, I am still encountering the 401 error. I would greatly appreciate any assistance or suggestions to resolve this.
Below is the code I'm using:
static void Main(string[] args)
{
string siteUrl = "https://****.sharepoint.com/sites/Casemanagement";
string clientId = "*************";
string clientSecret = "**************";
string tenantId = "**************";
string documentLibraryName = "Documents";
string folderPath = "457/457805/457805-002";
string accessToken = GetAccessToken(tenantId, clientId, clientSecret, siteUrl);
try
{
var context = new ClientContext(siteUrl);
context.ExecutingWebRequest += (sender, e) =>
{
e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + accessToken;
};
var web = context.Web;
var library = web.Lists.GetByTitle(documentLibraryName);
var folder = library.RootFolder.Folders.GetByUrl(folderPath);
var files = folder.Files;
context.Load(files);
context.ExecuteQuery();
Console.WriteLine("Files in folder:");
foreach (var file in files)
{
Console.WriteLine(file.Name);
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve files: {ex.Message}");
Console.ReadLine();
throw;
}
}
static string GetAccessToken(string tenantId, string clientId, string clientSecret, string resource)
{
try
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
.Build();
var result = app.AcquireTokenForClient(new string[] { "https://mddus.sharepoint.com/.default" }).ExecuteAsync().Result;
Console.WriteLine($"Token Expires On: {result.ExpiresOn}");
return result.AccessToken;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to acquire token: {ex.Message}");
throw;
}
}