0

I am trying to access the SP API from a C# app. I have tried several iterations of code with the end result of a 403. I am missing a key to make the parts click. I believe I have grown lazy in javascript. I would like this to operate like git or postman do, when you run the app if you haven't authenticated the login screen pops up for your pin. If you have logged in it uses that for auth. I thought that this was CredentialCache.DefaultCredentials but that is not working. There is no meaningful username since it's likely some guid from the CAC style card.

I have seen too many examples where they want you to code user/pass in. It's nearly 2024 I'm sure there is a better way.

I have verified the endpoint exists and returns a response in a browser.

My code follows: (I should change the namespace to FourOhThreeGenerator)

using System.Net;

namespace AuthForSPOnline
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("https://[tenent].sharepoint.com/teams/stst/_vti_bin/listdata.svc/test?$top=1&$orderby=Modified%20desc");

                endpointRequest.Method = "GET";
                endpointRequest.Accept = "application/json;odata=verbose";
                NetworkCredential cred = (NetworkCredential)System.Net.CredentialCache.DefaultCredentials;
                endpointRequest.Credentials = cred;
                HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                WebResponse webResponse = endpointRequest.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();

                Console.WriteLine(response);

                responseReader.Close();
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}

I appreciate help on this. I need to automate some things and this is my blocker.

0

Your Answer

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

Browse other questions tagged or ask your own question.