R – WPF WebBrowser Cookies to be used in WebRequest

cookieswebbrowser-controlwpf

I try to construct WebRequest to a web page after successful logging in to secured web portal via WPF WebBrowser control, but stuck with the problem of reusing WebBrowser cookies in WebRequest.

Unlike WinForms, in WPF WebBrowser control there is no way to extract CookieCollection via WebBrowser.Document.Cookies because Document object does not have Cookies property. The
only way I found is to use mshtml.HTMLDocument2 which has cookies as string

        mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)webBrowser.Document;
        string cookies = doc.cookie;

However it is not good enough as looks like MSHTML.Document2
– does not allow to extract important HttpOnly cookies (like ASP.Net_SessionID)
– and I need manually construct CookiesCollection object from Cookies string.

As a result, WebRequest with cookies constructed from string is failing with Session timeout error as ASP.Net_SessionID is not available.

Is there another way of building proper and completed CookieCollection object from WPF WebBrowser control?

Best Answer

Update: After EricLaw posted his comment, here is a snippet of code you could use to get an HttpOnly cookie:

    [DllImport("wininet.dll", SetLastError = true)]
    private static extern bool InternetGetCookieEx(string pchURL, string pchCookieName,
                   StringBuilder pchCookieData, ref System.UInt32 pcchCookieData,
                   int dwFlags, IntPtr lpReserved);

    private int INTERNET_COOKIE_HTTPONLY = 0x00002000;

    public void GetCookie()
    {
        string url = "http://www.bing.com";
        string cookieName = "ASP.NET_SessionId";
        StringBuilder cookie = new StringBuilder();
        int size = 256;
        InternetGetCookieEx(url, cookieName, cookie, ref size,
                            INTERNET_COOKIE_HTTPONLY, null)
    }

The value would be stored in the StringBuilder "cookie"

A more detailed example can be found in this MSDN blog post.

The only other possible way to get cookies from the WebBrowser that I know of is to use the InternetGetCookie method as mentioned in this StackOverflow answer.

However, it's not possible to get HttpOnly cookies as they are unretrievable as a security feature in browsers. This helps to prevent cross-site scripting. This works the same in WinForms as it does in WPF. More information on HttpOnly cookies can be found in the Wikipedia HTTP Cookie article.

Related Topic