0
votes

I have a .NET application that uses Sharepoint. In the application code, I am using ICredentials to specify a username and password which get assigned to the Credentials property of a ClientContext object.

This works fine, however, I would like to be able to hit Sharepoint from a REST tool like postman in order to test and debug requests more easily. I don't know how to specify the credentials in this case. I tried sending a basic auth header, but it didn't work.

Frank

1

1 Answers

0
votes

Sample code for your reference.

private static async Task<string> getWebTitle(string webUrl)
        {
            //Creating Password 
            const string PWD = "password";
            const string USER = "[email protected]";
            const string RESTURL = "{0}/_api/web?$select=Title";

            //Creating Credentials 
            var passWord = new SecureString();
            foreach (var c in PWD) passWord.AppendChar(c);
            var credential = new SharePointOnlineCredentials(USER, passWord);

            //Creating Handler to allows the client to use credentials and cookie 
            using (var handler = new HttpClientHandler() { Credentials = credential })
            {
                //Getting authentication cookies 
                Uri uri = new Uri(webUrl);
                handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

                //Invoking REST API 
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    string jsonData = await response.Content.ReadAsStringAsync();

                    return jsonData;
                }
            }
        }
        static void Main(string[] args)
        {

            //Creating Password 
            string webUrl = "https://tenant.sharepoint.com/sites/lee";
            var data=getWebTitle(webUrl).GetAwaiter().GetResult();
            Console.WriteLine("done");
            Console.ReadKey();
        }