Introduction
When we want to connect to SharePoint using client context, first, we need to import our SharePoint site certificate in our code to be able to connect to the SharePoint site. And, if we try to connect to the SharePoint site without a certificate, it will throw a 401 Unauthorized error.
Import and Export SharePoint Site Certificate
To download the SharePoint site certificate, please follow the below steps.
- Open the site in IE browser and click on the lock icon which is next to the address bar.
- Click on View Certificates - > Install Certificate.
- Open Certificate Import Wizard - > Next.
- Select "Certificate Store" option as “Place all certificates in the following folder” -> Browse the path and select Personal -> Finish. This will import the certificate.
- Open and Run command prompt -> Type “MMC”.
- Go to File -> Add/Remove Snap in -> Add “Certificates”.
- Expand Personal>Certificate folder.
- Right-click on the certificate that we imported in the previous step.
- Select All Tasks > Export > Give the certificate a name and save it to the local folder.
Create a clientcontext using certificate (C#)
Main Method
- static void Main(string[] args) {
- var ctx = new ClientContext("https://SharePointSiteUrl");
- ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
- bool validationResult = true;
- return validationResult;
- };
- ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
- ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(customXertificateValidation);
- ctx.ExecutingWebRequest += new EventHandler < WebRequestEventArgs > (context_ExecutingWebRequest);
- ctx.Credentials = CredentialCache.DefaultNetworkCredentials;
- }
Join the conversation! Your thoughts help the community grow.