SharePoint SE CSOM 403 Error

testUser 21 Reputation points
2025-02-17T02:12:51.9266667+00:00

I have both Windows Authentication as well as AAD(21v) Authentication turned on for my site, and when I try to get SharePoint data via CSOM, I get a 403 error!

Code:

ClientContext clientContext = new ClientContext("url");

clientContext.Credentials = new NetworkCredential("username", "password", "domain");

var web = clientContext.Web;

clientContext.Load(web);

clientContext.ExecuteQuery();

Console.WriteLine(web.Title); And I have tried the solution in the following blog:

https://unnieayilliath.com/2019/06/07/sharepoint-2013-2016-2019-use-csom-in-sharepoint-site-with-multiple-authentication-schemes/

And it would report 401 error.

Can anyone help me about this?

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
11,231 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,325 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,633 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 39,116 Reputation points Microsoft Vendor
    2025-02-17T07:23:14.2533333+00:00

    Hi @testUser,

    You could refer to following code to connect SharePoint SE

    using Microsoft.SharePoint.Client;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http.Headers;
    using System.Net.Http;
    using System.Security;
    using System.Security.Policy;
    using System.Security.Principal;
    using System.Text;
    using System.Text.Json;
    using System.Threading;
    using System.Threading.Tasks;
    using static System.Net.WebRequestMethods;
    
    
    namespace TestCoreConsoleApp
    {
        static class ProgramSP
        {
            private static string _siteUrl = "url of sp site";
            private static HttpWebRequest _webReq = null;
            private static Task<string> tokenTask = null;
            static void Main(string[] args)
            {
                tokenTask = GetDigestValueAsync(new CancellationToken());
                using (var clientContext = new ClientContext(_siteUrl))
                {
                    clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(AddWindowsAuthRequestHeader);
                    Web web = clientContext.Web;
    
                    clientContext.Load(web);
    
                    clientContext.ExecuteQuery();
                    Console.WriteLine(web.Title);
                    Console.ReadLine();
                }
            }
            private static void AddWindowsAuthRequestHeader(object sender, WebRequestEventArgs e)
            {
                try
                {
                    e.WebRequestExecutor.WebRequest.UseDefaultCredentials = true;
                    e.WebRequestExecutor.RequestHeaders["X-RequestDigest"] = tokenTask.Result;
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
    
            private static SecureString ConvertToSecureString(string password)
            {
                SecureString securePassword = new SecureString();
                foreach (char c in password)
                {
                    securePassword.AppendChar(c);
                }
                return securePassword;
            }
    
            private static async Task<string> GetDigestValueAsync(CancellationToken cancellationToken)
            {
    
                var endpointUrl = $"{_siteUrl}/_api/contextinfo";
    
    
                var handler = new HttpClientHandler
                {
                    UseDefaultCredentials = true,
                    PreAuthenticate = true
                };
                var client = new HttpClient(handler);
    
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.PostAsync(endpointUrl, null, cancellationToken);
    
                if (!response.IsSuccessStatusCode)
                    throw new Exception($"Error fetching digest value: {response.ReasonPhrase}");
    
                var responseContent = await response.Content.ReadAsStreamAsync(cancellationToken);
                var sharePointResp = await JsonSerializer.DeserializeAsync<DigestRoot>(responseContent,
                    new JsonSerializerOptions { PropertyNameCaseInsensitive = true }, cancellationToken);
    
                return sharePointResp?.FormDigestValue ?? throw new Exception("Failed to extract FormDigestValue");
            }
            public class DigestRoot
            {
                public string odatametadata { get; set; }
                public int FormDigestTimeoutSeconds { get; set; }
                public string FormDigestValue { get; set; }
                public string LibraryVersion { get; set; }
                public string SiteFullUrl { get; set; }
                public List<string> SupportedSchemaVersions { get; set; }
                public string WebFullUrl { get; set; }
            }
        }
    
    }
    
    

    If this doesn't work, please check the Credential on Postman by following steps

    https://www.miniorange.com/two-factor-authentication-(2fa)-for-sharepoint


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.