Reputation: 59
I have SharePoint subscription on-premise edition. Is there a way to connect to this instance using net6, csom and windows authentication?
I created console app and 'nuget' installed
<PackageReference Include="Microsoft.SharePointOnline.CSOM" Version="16.1.24009.12000" />
Then I tried following code
using (var clientContext = new ClientContext("url"))
{
Web web = clientContext.Web;
clientContext.Credentials = new NetworkCredential(@"userName", "Password");
//clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
//clientContext.Credentials = System.Net.CredentialCache.DefaultCredentials;
clientContext.Load(web);
clientContext.ExecuteQuery();
}
I tried using commented lines as well. Each time I get 401: Unauthorised.
Thank you
Upvotes: 0
Views: 855
Reputation: 59
I got it working as below -
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; }
}
}
}
With nuget package -
<PackageReference Include="Microsoft.SharePointOnline.CSOM" Version="16.1.24009.12000" />
Upvotes: 1