Thursday, May 1, 2014

Office 365 and SSO/ADFS

I have a customer who had an old integration with Office 365, which sync list items. The customer is now switched over to SSO/ADFS and the old code began to fail. The old code was built around building a cookie through MsOnlineClaimsHelper class:

1 string sharepointUrl = "https://<SharePointUrl>.sharepoint.com";
2 string username = "<username>@<domain>";
3 string password = "<passoword>";
4
5 using (Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext(sharepointUrl))
6 {
7 MsOnlineClaimsHelper helper = new MsOnlineClaimsHelper(username, password, sharepointUrl);
8 clientContext.ExecutingWebRequest += helper.clientContext_ExecutingWebRequest;
9 Microsoft.SharePoint.Client.Web web = clientContext.Web;
10 clientContext.Load(web, w => w.Title);
11 clientContext.ExecuteQuery();
12 Console.WriteLine(web.Title);
13 }

When the code runs gives the error:
"An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail."
error 
But instead of using MsOnlineClaimsHelper, then there is a new SharePointOnlineCredentials class in SharePoint.Client CSOM api that will fix this error.



1 string sharepointUrl = "https://<SharePointUrl>.sharepoint.com";
2 string username = "<username>@<domain>";
3 string password = "<passoword>";
4
5 SecureString passWordString = new SecureString();
6 foreach (char c in password.ToCharArray()) passWordString.AppendChar(c);
7
8 Microsoft.SharePoint.Client.SharePointOnlineCredentials credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, passWordString);
9
10 using (Microsoft.SharePoint.Client.ClientContext clientContext = new Microsoft.SharePoint.Client.ClientContext(sharepointUrl))
11 {
12 clientContext.Credentials = credentials;
13
14 Microsoft.SharePoint.Client.Web web = clientContext.Web;
15 clientContext.Load(web, w => w.Title);
16 clientContext.ExecuteQuery();
17 Console.WriteLine(web.Title);
18 }

If you need the auth cookie for like a webservice call or a REST call you can get the cookie like this


1 ListService.Lists listService = new ListService.Lists();
2 Uri sharepointuri = new Uri(sharepointUrl);
3 string authCookie = credentials.GetAuthenticationCookie(sharepointuri);
4 listService.CookieContainer = new System.Net.CookieContainer();
5 listService.CookieContainer.Add(new System.Net.Cookie("FedAuth", authCookie.Replace("SPOIDCRL=", string.Empty), string.Empty, sharepointuri.Authority));
6 listService.UseDefaultCredentials = false;

No comments:

Post a Comment