In my previous post in this series I talked about how authentication works with Office365 (O365) & SharePoint Online (SPO). You first authenticate with Microsoft Online (MSO) and then your browser passes along the SAML token with each request to site collections in SPO.

The first thing we need to do when accessing SPO programmatically is to understand how we authenticate with MSO and get the SAML token. Thankfully Microsoft provides a sample to help with the authentication piece. What you need is to make sure you have the Windows Identity Framework Runtime installed first. The main class that Wictor Wilen provides for authenticating to MSO is MsOnlineClaimsHelper. This class takes three parameters in the constructor:

MSO Username of the account to authenticate with

MSO Password of the account to authenticate with

URL of the root site collection for your SPO account - note this is the root site collection which may not necessarily be the site collection you are interested in, but it is needed to authenticate and get the key

The MsOnlineClaimsHelper class has a public property, CookieContainer (which is also of type System.Net.CookieContainer), that you'll use to get the SAML token from MSO to attach to future requests. When the CookieContainer property is accessed, if null, the MsOnlineClaimsHelper will go authenticate and parse the results to extract the SAML token and store it in the cookie container.

Check out the code sample I mentioned previously in this post. What you're looking for are two files in the MSDN folder of the ACsCichlids.StoreFront project & the CSOM redistributable. These two files are the aforementioned MsOnlineClaimsHelper.cs & a file it depends on, WcfClientContracts.cs. Copy them into your project and that's all you need in order to authenticate.

Here's just a little code from a simple console app that shows me authenticating into my SharePoint Online site collection: