0

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: User's image

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. The access token is successfully being created but 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;
    }
}
1
  • A 401 Unauthorized error when using the Microsoft.SharePoint.Client (CSOM) API typically indicates that the application does not have the necessary permissions or that the access token is not being accepted by SharePoint. Commented Jan 15 at 7:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.