Search code examples
c#cookiespostshdocvw

How to send a cookie in a POST using SHDocVw.InternetExplorer.Navigate?


Problem: In our organization we have a home grown single-sign-on app written in c#/.Net2 that has been working for years. We recently found that the app doesn’t work with Outlook Web Access 2010. A few web searches turned up a couple articles from SSO vendors (Novell KB and Citrix KB) that refer to the issue. OWA2010 executes a javascript on submit that adds a cookie called “PBack=0” that if not included in the post will result in an authentication failure.

Question: How can I include a cookie in the Navigate method of SHDocVw.InternetExplorer?

//ie2 is the instance of IE (SHDocVw.InternetExplorer) containing the OWA login page
ie2.Navigate(URLToPostTo, ref vFlags, ref vTarget, ref vPost, ref vHeaders);

Solution

  • This c# code performs single sign on for owa 2010 in Internet explorer.

     AutoResetEvent documentCompleteOW2010;
        void OWA2010LaunchAndSSO()
        {
            var sURL "https://owaserver.yourorg.org/owalogon.asp?
    
            SHDocVw.InternetExplorer explorer = new SHDocVw.InternetExplorer();
            explorer.Visible = true;
            explorer.DocumentComplete += OnIEDocumentCompleteOWA2010; // Setting the documentComplete Event to false            
            documentCompleteOW2010 = new AutoResetEvent(false);
            object mVal = System.Reflection.Missing.Value;
            explorer.Navigate(sURL, ref mVal, ref mVal, ref mVal, ref mVal);// Waiting for the document to load completely            
            documentCompleteOW2010.WaitOne(5000);
    
            try
            {
                mshtml.HTMLDocument doc = (mshtml.HTMLDocument)explorer.Document;
                mshtml.HTMLInputElement userID = (mshtml.HTMLInputElement)doc.all.item("username", 0);
                userID.value = "someADUserName";
    
                mshtml.HTMLInputElement pwd = (mshtml.HTMLInputElement)doc.all.item("password", 0);
    
                pwd.value = "someADPassword";
                mshtml.HTMLInputElement btnsubmit = null;
                var yada = doc.getElementsByTagName("input");
                foreach (var VARIABLE in yada)
                {
                    var u = (mshtml.HTMLInputElement)VARIABLE;
                    if (u.type == "submit")
                    {
                        btnsubmit = u;
                    }
                }
                btnsubmit.click();
    
            }
            catch (Exception err)
            {
                //do something
            }
            finally
            {
                //remove the event handler
                explorer.DocumentComplete -= OnIEDocumentCompleteOWA2010;
            }
        }
    
        private void OnIEDocumentCompleteOWA2010(object pDisp, ref object URL)
        {
            documentCompleteOW2010.Set();
        }