Using WebRequest to obtain cookies to automaticall

2019-04-02 18:04发布

问题:

I am following this tutorial to authenticate for Sharepoint Online remotely, but I'm doing it in C#.

http://allthatjs.com/2012/03/28/remote-authentication-in-sharepoint-online/

I can get the SAML from STS with no problem, but I can't seem to send this token to Sharepoint to recieve back the Cookies in order to log in. Below is my code, excuse any glaring errors, I'm new at this!

 //Send cookie to SPO. The token is from STS.
        byte[] spbyteArray = Encoding.UTF8.GetBytes(theToken);
        WebRequest sprequest = WebRequest.Create("https://login.microsoftonline.com/login.srf?wa=wsignin1.0&rpsnv=2&ct=1335885737&rver=6.1.6206.0&wp=MBI&wreply=https%3A%2F%2Fcamida.sharepoint.com%2F_forms%2Fdefault.aspx&lc=1033&id=500046&cbcxt=mai&wlidp=1&guest=1");
        sprequest.Method = "POST";
        sprequest.ContentLength = spbyteArray.Length;
        sprequest.ContentType = "application/x-www-form-urlencoded";
        sprequest.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, sprequest.Headers, new object[] { "Host", "mydomain.sharepoint.com" });
        Stream spdataStream = sprequest.GetRequestStream();
        spdataStream.Write(spbyteArray, 0, spbyteArray.Length);
        spdataStream.Close();

        //Get response from SPO
        WebResponse spresponse = sprequest.GetResponse();
        spdataStream = spresponse.GetResponseStream();
        StreamReader spreader = new StreamReader(spdataStream);

        // Read the content.
        string spresponseFromServer = spreader.ReadToEnd();

If I use the URL in the tutorial I get a 403 forbidden. The URL I am using is the one it redirects to when I got to http://mydomain.sharepoint.com

Any help and advice is greatly appreciated.

回答1:

When requesting from SharePoint you have to set the User Agent or else it returns a 403 This line;

 sprequest.UserAgent = "Mozilla/5.0 (Windows NT 6.0; rv:12.0) Gecko/20100101 Firefox/12.0";

Is all it took.



回答2:

It doesn't look like you are adding any cookies, which might be required. If you cast your WebRequest to an HttpWebRequest, you can work with cookies. See c# WebRequest using WebBrowser cookie.

Also, I would become familiar with a tool like Fiddler in order to inspect requests and responses that you send from your browser. This allows you to see exactly what is being sent back and forth, so that you can attempt to duplicate/emulate the requests in C#.