Search This Blog

Tuesday 26 January 2016

Call/Connect to SharePoint from C# with NLTM authentication

I need to call a rest service hosted in SharePoint 2010 from C# .Net.
SharePoint uses NLTM authentication. So basic authentication wont work.

Initially i tried using
1. HttpClient
2. WebRequest
3. HttpWebRequest

My trail codes:
//1----
                // validate cert by calling a function
                //ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                var creds = new NetworkCredential("<domain\un>","Password");
                string myreq = @"{ProgramID:6}";
                String MyURI = new Uri("<myserviceurl>").ToString();
                WebRequest WReq = WebRequest.Create(MyURI);
                WReq.Method = "POST";
                WReq.Credentials = creds;
                    var res = WReq.GetResponse();
//2--------
string jsonRequest = "<myServiceUrl>";

                HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(jsonRequest);
                spRequest.Credentials = credCache;
                spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
                spRequest.Method = "POST";
                spRequest.Accept = "application/json; odata=verbose";
                HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
//3--------
                var handler = new HttpClientHandler{Credentials = creds};
               
                using(var http = new HttpClient(handler)){
                   
                    http.DefaultRequestHeaders.Clear();
                    http.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                    //http.DefaultRequestHeaders.Add("X-RequestDigest", digest);
                    http.DefaultRequestHeaders.Add("X-RequestDigest", "digest");
                    http.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");

                    var mediaType = new MediaTypeHeaderValue("application/json");
                    //var jsonSerializerSettings = new JsonSerializerSettings();
                    //var jsonFormatter = new JsonNetFormatter(jsonSerializerSettings);
                    //var requestMessage = new HttpRequestMessage<T>(data, mediaType, new MediaTypeFormatter[] { jsonFormatter });
                    StringContent content = new StringContent(myreq);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");//, Encoding.UTF8, "application/json");
                    //content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                    //content.Headers.ContentLength = myreq.Length;

                   
                   
                    http.BaseAddress = new Uri("<serviceurl>");
                   
                    resp = http.PostAsync("serviceurl",content).Result;
                }

NOTHING ABOVE WORKED. ITS ALL CREDENTIALS PROBLEM.
The below has worked: using CredentialCache
//4--
                string json = "{\"ProgramID\":\"6\"}";
                HttpWebRequest req = WebRequest.Create(MyURI) as HttpWebRequest;
                req.Method = "POST";
                req.ContentType = "application/json";
                req.ContentLength = json.Length;
                
                CredentialCache credCache = new CredentialCache();
                credCache.Add(new Uri(MyURI), "NTLM", new NetworkCredential("<un>", "Password"));
                req.Credentials = credCache;
                using (StreamWriter requestStream =new StreamWriter(req.GetRequestStream()))
                {
                    requestStream.Write(json);
                    requestStream.Flush();
                    requestStream.Close();

                }

                HttpWebResponse myres = req.GetResponse() as HttpWebResponse;
                using (var streamReader = new StreamReader(myres.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();

                }

No comments:

Post a Comment