Access SharePoint Online Using CSOM .NET Standard Version APIs

What is alternative of the App Only Access method to connect SharePoint from the external system? Lot’s of user voices came around the world.
Long awaited .NET Standard Version of SharePoint Online CSOM was released on 23rd June,2020.
Click Here to get article for official announcement from Microsoft.
As we aware that Microsoft is investing tremendously in Microsoft Graph.
Still certain capabilities is not exposed yet in #MsGraphAPI. In that case we might need to come back to use of CSOM API.

Authentication is totally independent of CSOM library as compared .NET framework.
Authentication using SharePointOnlineCredentials is not possible in Standard version.
Click here to get more differences
.NET Standard works based on OAuth access token and it’s developer responsibility to taken care of while making calls to SharePoint Online.

Let’s have a look getting application authentication access token through Azure AD registered application.

The recommended approach is to go with an Azure AD App Registration and the Client Certificate approach so that is what we will be using.
Steps:
1. Registered Application in Azure Active Directory
2. Grant API(SharePoint) Permission based on your requirement.
3. Generate Client Secrete Key
4. Set “Treat application as a public client” to yes under authentication
5. Copy Client ID and Client Secrete
Click here for Microsoft document to grant access via Azure AD.

Add Secrete key

The consented SharePoint permissions:

Let’s move to coding side.
Prerequisites NuGet packages
1. Microsoft.SharePointOnline.CSOM : version 16.1.20211.12000
2. Microsoft.Identity.Client : version 4.15.0
I am using .NET core 3.1 console application project with VS2019.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.Identity.Client;
using System.Threading.Tasks;
namespace CSOMStandardAPI
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string siteURL = "https://tenant.sharepoint.com/sites/DMS";
            string clientId = "b9233822-cdde-40b0-8c0c-4b23cf162520"; // Get client ID from Azure AD
            string secrete = "1PRtz-rU1eX._lkf_654K~fZ3gU5_0r7j4";// Get Client Secrete from Azure AD
            string tenantId = "tenant.onmicrosoft.com";
            var scopes = new string[] { "https://tenant.sharepoint.com/.default" };

            var accessToken = await GetAuthenticatedClientAccessToken(clientId, secrete, scopes, tenantId);
            var clientContext = GetClientContext(siteURL, accessToken);
            Web web = clientContext.Web;
            clientContext.Load(web);
            clientContext.ExecuteQuery();
            Console.WriteLine(web.Title);
            Console.ReadKey();
        }
        
        internal static async Task<string> GetAuthenticatedClientAccessToken(string clientId, string secrete, string[] scopes, string tenantId)
        {
            IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                            .Create(clientId)
                                            .WithClientSecret(secrete)
                                            .WithTenantId(tenantId)
                                            .Build();

            AuthenticationResult authResult = await clientApp.AcquireTokenForClient(scopes).ExecuteAsync();
            string accessToken = authResult.AccessToken;
            return accessToken;
        }
        public static ClientContext GetClientContext(string targetUrl, string accessToken)
        {
            ClientContext clientContext = new ClientContext(targetUrl);
            clientContext.ExecutingWebRequest +=
                delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
                {
                    webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                        "Bearer " + accessToken;
                };
            return clientContext;
        }

    }
}

Run console application using F5 and you will get your site collection Title in console application.

Sharing is Caring

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.