0

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);
        //requestWriter.Write(data);
        requestWriter.Close();

        try
        {
            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
            responseReader.Close();
        }
        catch (Exception e)
        {
            Console.Out.WriteLine("-----------------");
            Console.Out.WriteLine(e.Message);
        }
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);
0

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);
   context.ExecuteQuery();
   Console.WriteLine("Your site title is: " + context.Web.Title);
}

References:

  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, privacy policy and cookie policy

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