I am using the code below and am getting unauthorized access. Can you guys show me what i am missing here.I am using SharePoint 2019.

  string URL = "http://sharepoint/sites/test/_api/search/query?querytext="+"SharePoint";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        //request.ContentLength = DATA.Length;
        StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);

            WebResponse webResponse = request.GetResponse();
            Stream webStream = webResponse.GetResponseStream();
            StreamReader responseReader = new StreamReader(webStream);
            string response = responseReader.ReadToEnd();
            Console.Out.WriteLine(response); //Get Web response and proceed accordingly
        catch (Exception e)

2 Answers 2


If you just want to authenticate as yourself, as in the user who is executing the code, you can pass default credentials with:

request.UseDefaultCredentials = true;

Ganesh's answer works fine for SharePoint online using CSOM, but since you're on 2019 and using HttpWebRequest, if you want to authenticate as someone other than the user executing the code, you can use:

request.Credentials = new NetworkCredential(UserName, PassWord);

You can use code like given below for Authentication:

using (var context = new ClientContext(webUrl))
   context.Credentials = new SharePointOnlineCredentials(userName,password);
   context.Load(context.Web, web => wweb.Title);
   Console.WriteLine("Your site title is: " + context.Web.Title);


  1. Remote Authentication using C# CSOM for SharePoint online site
  2. Authentication to Sharepoint Online with CSOM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.