Connecting to SharePoint online programmatically using REST in .Net

How to connect SharePoint Online using web request:

  1. Get the authentication token from https://login.microsoftonline.com/extSTS.srf using SAML. SAML token has xml format in which it takes user name, password and  token provider URL.  You can put placeholders in the xml template to replace these dynamic contents.

Below is SAML template:

“<?xml version=\”1.0\” encoding=\”utf-8\” ?><s:Envelope xmlns:s=\”http://www.w3.org/2003/05/soap-envelope\” xmlns:a=\”http://www.w3.org/2005/08/addressing\” xmlns:u=\”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\”><s:Header><a:Action s:mustUnderstand=\”1\”>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo><a:To s:mustUnderstand=\”1\”>https://login.microsoftonline.com/extSTS.srf</a:To><o:Security s:mustUnderstand=\”1\” xmlns:o=\”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\”><o:UsernameToken><o:Username>[username]</o:Username><o:Password>[password]</o:Password></o:UsernameToken></o:Security></s:Header><s:Body><t:RequestSecurityToken xmlns:t=\”http://schemas.xmlsoap.org/ws/2005/02/trust\”><wsp:AppliesTo xmlns:wsp=\”http://schemas.xmlsoap.org/ws/2004/09/policy\”><a:EndpointReference><a:Address>[endpoint]</a:Address></a:EndpointReference></wsp:AppliesTo><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType></t:RequestSecurityToken></s:Body></s:Envelope>”;

  1. In response we will get binary security token and expiry time along with other data. Hence we need  to filter out these values form response.

// parse the token response

          XDocument doc = XDocument.Parse(strLoginPostContent);

          // get the security token

          var crypt = from result in doc.Descendants()

                      where result.Name == XName.Get(“BinarySecurityToken”, wsse)

                      select result;

          // get the token expiration

          var expires = from result in doc.Descendants()

                        where result.Name == XName.Get(“Expires”, wsu)

                        select result;

          var exp = Convert.ToDateTime(expires.First().Value);

  1. As we are relying on authentication cookies to make any API call to SharePoint online, hence need to retrieve values of two cookies i.e. FedAuth and rtFa by appending “/_forms/default.aspx?wa=wsignin1.0” to site URL. From response extract value of above two cookie value.

 

authCookie.FedAuth = webResponse.Cookies[“FedAuth”].Value;

authCookie.RtFa = webResponse.Cookies[“rtFa”].Value;

  1. In Last step we will make a web request by attaching the above two cookies for every request (the example shown fetches webs from SharePoint online) to get actual data.

var cookie = GetAuthToken(tokenSPUrl, userName, password);

var rootWebUrl = siteUrl + “_api/web/webs”; // need to change as per information you want to fetch like List ,Web, Role.

var webRequest = (HttpWebRequest)WebRequest.Create(rootWebUrl);

webRequest.Method = “GET”;

webRequest.Accept = “application/json; odata=verbose”;

// webRequest.ContentType = “text/xml; charset=utf-8”;

webRequest.UserAgent = USER_AGENT;

webRequest.CookieContainer = new CookieContainer();

webRequest.CookieContainer.Add(new Cookie(“FedAuth”, cookie.FedAuth,”/” ,”provide your domain name like test.com”));

webRequest.CookieContainer.Add(new Cookie(“rtFa”, cookie.RtFa, “/”, “provide your domain name like test.com”));

 

string strRes = null;

using (var res = webRequest.GetResponse() as HttpWebResponse)

{

using (var sr = new StreamReader(res.GetResponseStream()))

{

strRes = sr.ReadToEnd();

Console.WriteLine(“Sample response: ” +strRes);

}

}

You can download full sample from URL