Authenticating client with office 365/SharePoint online

Atul Sureka picture Atul Sureka · Jan 6, 2014 · Viewed 34.3k times · Source

I have a client application which consumes SharePoint web service (list.asmx). Recently SharePoint is migrated to SharePoint Online. Now authentication is failing.

This might be because authentication mechanism is different in SharePoint Online. I referred the article http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx for doing the authentication. However for some reason I am getting Authentication error now.

Please note I do not want authentication window to pop-up, as my client is a service.

Can anybody please give me some pointer/sample working application on how to do authentication with SharePoint Online?

Atul Sureka

Answer

Vadim Gremyachev picture Vadim Gremyachev · Feb 18, 2015

SharePoint Online (SPO) uses claims-based authentication mode. Microsoft released SharePoint Online Client Components SDK which contains SharePointOnlineCredentials class that could be utilized for SharePoint Web Services authentication in SPO.

How to authenticate SharePoint Web Services in SharePoint Online (SPO)

The following example demonstrates how to retrieve authentication cookies:

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;
}

Example

string sourceUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide.docx";
string destinationUrl = "https://contoso.sharepoint.com/Documents/SharePoint User Guide 2013.docx";
FieldInformation[] fieldInfos;
CopyResult[] result;
byte[] fileContent;
using(var proxyCopy = new Copy())
{
     proxyCopy.Url = webUri + "/_vti_bin/Copy.asmx";
     proxyCopy.CookieContainer = GetAuthCookies(webUri, userName, password);

     proxyCopy.GetItem(sourceUrl,out fieldInfos,out fileContent);
     proxyCopy.CopyIntoItems(sourceUrl,new []{ destinationUrl}, fieldInfos, fileContent, out result);
 }

References