Azure, C#, Microsoft365

Connecting to SharePoint Online using an Azure AD Service Principle (Application) and CSOM

2 min read

Microsoft is giving us a push to use Microsoft Graph as an alternative to using SharePoint CSOM. Unfortunately, not everything is available in Microsoft Graph. When you are automating, you want to use a service account that has no user identity (delegation) in it and can be autonomous. However, the only way right now to get an application token that can be used to consume the SharePoint Online CSOM, is to authenticate your application using an authentication certificate.

This post continues on the SPOAuthentication code, as discussed in my other post.

We will make use of the KeyVault to store the authentication certificate and then add it to the application as a key credential used for authentication.

KeyVault and Application setup

KeyVault

Generate or add a certificate in the KeyVault to use for the authentication. In my case, I generated a self-signed certificate with the name as SPO<AppName>Authentication and the subject CN=SPO<AppName>Authentication, where <AppName> is the name of my Azure AD application.

Keyvault create authentication certificate

Adding the certificate to the Application

Time to add the certificate to the application. To do that we can do it with either the az cli or PowerShell.

PowerShell:

az cli:

Once added, you should see in the application manifest, under the keyCredentials property, something like this:

Adding the code to the SPOAuthenticationManager

In my other post, I used a delegate to manage the token fetching. In this scenario, we create another overload of the GetContext method, and have a different delegate body that will fetch the token using the provided certificate.

GetContext method:

AcquireTokenAsync method:

As you can see, we authenticate through a client_credential grant, using the certificate passed as parameter.

Tying everything together

In the console application, we now need to grab the certificate from the keyVault and pass it to our authentication manager.

Grabbing the certificate

To grab the certificate, you can use the new Azure.Security.KeyVault.Secrets library. If you are not aware of the new Azure.Security.KeyVault.* libraries, check out my post on that subject!

Calling SharePoint CSOM

We can then call the API using the CSOM library

Conclusion

As you can see you can authenticate using a certificate and generate yourself a token to consume SharePoint CSOM.

You can use the same token to query the REST API (_api/*). If you wish to do that, you can use a similar logic (authenticate your user, swap for a delegated token, cache the token, etc.) and use it within a DelegatingHandler that will be responsible to acquire the token and add it to your Authentication header. Voila!