Monday, March 2, 2015

Accessing SharePoint Online with Web Client

Misleading title really because if you try and access SharePoint Online using the WebClient it will fail to authenticate.  What you need to do is use the CookieContainer and SharePointOnlineCredentials. 
I got the basics of this from this post. and also from this post which uses a class inherits from WebClient. It mentions that you need the SharePoint Client Components SDK which will install Microsoft.SharePoint.Client.DLL and Microsoft.SharePoint.Client.RunTime.DLL. Add references to both DLLs in your project and add these two using statements

using Microsoft.SharePoint.Client;
using System.Security;


 
Add this class to your project
 
public class ClaimsWebClient : WebClient
{ private CookieContainer cookieContainer;

public ClaimsWebClient(Uri host, string userName, string password)
 
{

cookieContainer = GetAuthCookies(host, userName, password);

}
 
protected override WebRequest GetWebRequest(Uri address)
{
    WebRequest request = base.GetWebRequest(address);
    if (request is HttpWebRequest)
 
    { 
        (request as HttpWebRequest).CookieContainer = cookieContainer;
   }
  
   return request;
 
}
 
private static CookieContainer GetAuthCookies(Uri webUri, string userName, string password)
{    var securePassword = new SecureString();
    foreach (var c in password) { securePassword.AppendChar(c); }
    var credentials = new SharePointOnlineCredentials(userName, securePassword);
    var authCookie = credentials.GetAuthenticationCookie(webUri);
    var cookieContainer = new CookieContainer();
    cookieContainer.SetCookies(webUri, authCookie);      return cookieContainer;
}

}
 


Then call the ClaimWebClient class in the same way as you would the WebClient.  Note that you do not need to set the credentials because it is done within the ClaimWebClient class.

ClaimsWebClient wc = new ClaimsWebClient(new Uri(sharePointSiteUrl), userName, password);

byte[] response = wc.DownloadData(sourceUrl);
 

2 comments: