Forum Discussion

dhanushaelangovan's avatar
dhanushaelangovan
Copper Contributor
Feb 12, 2025

401 unauthorised for ExecuteQuery in sharepoint CSOM

Hi,

I am trying to connect the sharepoint site with client id and secret but getting 401 unauthroised error while hitting the executequery() method.

While doing app registrations both Microsoft graph and share point API permissions with full site control has been given including trusted the app through appinv.aspx. Still getting 401 unauthorised error.

Since ACS is retiring, do we need to follow any other permissions for share point level site access. The same execute query is working fine for client id, certificate combination. But not working for client id and secret.

 

static void Main(string[] args)
        {

            var authManager = new AuthenticationManager("***************************", "C:\\Program Files\\OpenSSL-Win64\\bin\\certificate.pfx", "*******", "********.onmicrosoft.com");
            using (var cc = authManager.GetContext("https://****.sharepoint.com/sites/****"))
            {
                cc.Load(cc.Web, p => p.Title);
                cc.ExecuteQuery();
                Console.WriteLine(cc.Web.Title);
                ListCollection listCollection = cc.Web.Lists;
                cc.ExecuteQuery(); // this is working fine
            };
            // Replace with your SharePoint Online details
            string siteUrl = "****************************";
            string tenantId = "***************************";
            string clientId = "********************************";
            string clientSecret = "******************************"; // App secret

            try
            {
                using (var context = GetClientContextWithOAuth(siteUrl, tenantId, clientId, clientSecret))
                {
                    // Example: Retrieve web title
                    Web web = context.Web;
                    context.Load(web, w => w.Title);
                    context.ExecuteQuery(); // this is throwing 401 unauthorized error

                    Console.WriteLine("Connected to: " + web.Title);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        private static ClientContext GetClientContextWithOAuth(string siteUrl, string tenantId, string clientId, string clientSecret)
        {
            // Azure AD OAuth 2.0 endpoint
            string authority = $"https://login.microsoftonline.com/*******************";

            // Use MSAL to acquire an access token
            var app = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri(authority))
                .Build();

            var authResult = app.AcquireTokenForClient(new[] { $"{siteUrl}/.default" }).ExecuteAsync().Result;

            if (authResult == null)
            {
                throw new Exception("Failed to acquire the access token.");
            }

            // Use the access token to authenticate the ClientContext
            var context = new ClientContext(siteUrl);
            context.ExecutingWebRequest += (sender, e) =>
            {
                e.WebRequestExecutor.WebRequest.Headers["Authorization"] = "Bearer " + authResult.AccessToken;
            };

            return context;
        }

No RepliesBe the first to reply

Resources