Friday, September 11, 2015

Authenticate to Office 365 and SharePoint Online option #2 - REST using SharePointOnlineCredentials object from C#

When working on SharePoint Online as a new developer, there is always some confusion how to connect and authenticate to the SharePoint site. I’m summarizing all the different authenticate ways so my developers could choice one appropriate approach for their projects.


In this blog, I’ll illustrate the C# REST example using SharePointOnlineCredentials object. In this case, you need to pass the user name, password, and the REST end point. The following example illustrated the REST API to get list from title and get all items from one list.


using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Newtonsoft.Json.Linq;

namespace RESTClient
{
    class Program
    {
        static void Main(string[] args)
        {
            const string siteURL = "https://mycompany.sharepoint.com/sites/SPDEV";
            const string actionREST = siteURL + "/_api/web/lists/getbytitle('TestList')";
            const string userName = "userID@mycompany.com";
            const string password = "mypassword";

            // Get the list jason result
            Task<string> result = getRestResult(siteURL, actionREST, userName, password);
            result.Wait();
            string jasonResult = result.Result;
            Console.WriteLine(jasonResult);

            // Get list Title from jason result
            var obj = JObject.Parse(jasonResult);
            var title = (string)obj.SelectToken("Title");
            Console.WriteLine(title);

            // Get all items jason result
            const string actionRESTItem = siteURL + "/_api/web/lists/getbytitle('TestList')/items";
            Task<string> resultItems = getRestResult(siteURL, actionRESTItem, userName, password);
            resultItems.Wait();
            string jasonItemResult = resultItems.Result;
            Console.WriteLine(jasonItemResult);

            // Get each item from jason result


        }

        private static async Task<string> getRestResult(string siteURL, string actionREST, string userName, string password)
        {

            //Creating SharePointOnlineCredentials 
            var securePW = new SecureString();
            foreach (var c in password) securePW.AppendChar(c);
            var credential = new SharePointOnlineCredentials(userName, securePW);

            //Creating Handler to allows the client to use SharePointOnlineCredentials
            using (var handler = new HttpClientHandler() { Credentials = credential })
            {
                //Getting authentication cookies 
                Uri uri = new Uri(siteURL);
                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(actionREST).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

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


    }
}

The nest step is to parse the jason return string to get each item details. We will provide examples in the future.

No comments:

Post a Comment