Part 2: “Headless” Authentication with SharePoint Online and the Client Side Object Model

This is a continuation from my last post:  Authentication with SharePoint Online and the Client Side Object Model

Part 1 tackled how to authenticate and get data from SharePoint Online (SPO) in a client application like a Windows application.  This included popping up a browser in a dialog window where the user could enter their Office 365 credentials, and then attaching the authentication cookies Office 365 issued to the SharePoint Client Side Object Model (CSOM) to query to your SPO site.

This works great for when a user is involved, but its not a good solution if you client code is a service or another application where a user isn’t present. 

To deal with this scenario the code needs to effectively BE the user and login on their behalf.

To do this this sample queries the Office 365 STS directly using the Windows Identity Foundation (WIF).  WIF helps with managing the security tokens and requests to the STS. 

Note: To run this sample you need to have the WIF runtime installed from here .

At a high level this sample:

  • Uses WIF to login the user with the Office 365 STS
  • Extracts the Authentication Cookies from the response (“FedAuth” and “rtfa”)
  • Constructs a CookieContainer with those cookies
  • Attaches the CookieContainer to the CSOM web request
  • Calls your SPO site and returns the Title property of the site

Usage:  Compile the project and then run the ExampleCmdLine.exe like this:

ExampleCmdLine.exe <spo site url> <spo username> <spo password>

e.g. ExampleCmdLine.exe pass@word1

PS: those are not really my credentials … don’t bother trying to run that example :)

Note:  Its important you use HTTPS in your site url.  It wont work otherwise.

Credits:   I am not clever enough to work this stuff out.  I need all the help I can get.  There were two people instrumental in putting this together.  I simply took from their examples and put it into  a simple example/package and tweaked a few things.

  • Steve Peschka.  Excellent posts on this topic, here here and here
  • Wictor Wilén.  Did a talk on this topic a while back, and who’s presentation and sample code is here

Before you can run this you will need to install:

Unzip, compile and run from a command prompt.  All things going well it will return you the title of your SPO site.