Wednesday 8 February 2017

SharePoint Online: Authenticating .NET Client Object Model in Office 365

Below the sample code:
   You will need to reference the Microsoft.SharePoint.Client.dll and the Microsoft.SharePoint.Client.Runtime.dll assemblies in your project.

     static void Main(string[] args)
            {          
               Task<string> result = getWebTitle("https://<domain>/sites/testing");
                    result.Wait();
                    Response.Write(result.Result);
            }

      private static async Task<string> getWebTitle(string webUrl)
            {
              
                const string PWD = "******";
                const string USER = "username";
                const string RESTURL = "{0}/_api/web/lists/getbytitle('PictureLibrary')/items(2)/File";    
                var passWord = new SecureString();
                foreach (var c in PWD) passWord.AppendChar(c);
                var credential = new SharePointOnlineCredentials(USER, passWord);
               
                using (var handler = new HttpClientHandler() { Credentials = credential })
                {
                    Uri uri = new Uri(webUrl);
                    handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
                    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;
                    }
                }
            }

No comments:

Post a Comment