These two articles describe how to register an app in Azure AD that requests SharePoint app only permissions and then how to use that app registration with Client Object Model code. Please note, that the Client Object Model does not support the use of client Id and client secret for authentication when using app-only permissions. You must instead use client Id and a certificate. This is covered in the linked articles.
Accessing SharePoint using an application context, also known as app-only
Granting access via Azure AD App-Only
Here's the sample code that's included in the second article. It uses the PnP Framework for authentication.
using PnP.Framework;
using System;
namespace AzureADCertAuth
{
class Program
{
static void Main(string[] args)
{
var authManager = new AuthenticationManager("<application id>", "c:\\temp\\mycert.pfx", "<password>", "contoso.onmicrosoft.com");
using (var cc = authManager.GetAzureADAppOnlyAuthenticatedContext("https://contoso.sharepoint.com/sites/demo"))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
};
}
}
}
Here's some sample code that does the same thing using the Microsoft Authentication Library (MSAL) for authentication. You'll need to add the Microsoft.Identity.Client (MSAL) and Microsoft.SharePointOnline.CSOM Nuget packages to your project to use the code below.
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace CsomAzureTest
{
class Program
{
private static string tenantName = "contoso";
static void Main(string[] args)
{
CallClientObjectModel().Wait();
}
private async static Task<string> GetAccessToken()
{
var clientId = "<client id>";
var certFileName = @"C:\temp\mycert.pfx";
var certPassword = "<password>";
var certificate = new X509Certificate2(certFileName, certPassword,
X509KeyStorageFlags.MachineKeySet);
var authority = $"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com/";
var azureApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithCertificate(certificate)
.Build();
var scopes = new string[] { $"https://{tenantName}.sharepoint.com/.default" };
var authResult = await azureApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
private async static Task CallClientObjectModel()
{
var token = await GetAccessToken();
var siteUrl = $"https://{tenantName}.sharepoint.com/sites/demo";
using (var context = new ClientContext(siteUrl))
{
context.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + token;
};
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(web.Title);
}
}
}
}