Getting webbrowser cookies to log in

Jaanus picture Jaanus · Feb 24, 2013 · Viewed 27.8k times · Source

I am creating an windows forms app, where I have a webbrowser control.

After user logs in with the webbrowser, I want to log in also with same account with Microsoft.Http.HttpClient or HttpWebRequest or similar, it should be similar to cURL from PHP.

Problem is that the webpage allows only single sign on per account and if I sign with HttpClient, it will kick the webbrowser out.

What I want to know, if it is possible to hijack webbrowser session or get the cookies and use it in my HttpClient or similar api.

I can use webbrowser.Cookie to get some data, but how to push it to HttpClient?

Is that kind of thing even possible, that I can just take the cookies and use the same session? If so, how?

Answer

Jaanus picture Jaanus · Feb 24, 2013

Got help from here:

Is it possible to transfer authentication from Webbrowser to WebRequest

Alkampfer posted solution. This is exactly what I needed and it worked.

This solution also takes Http only cookies.

You can call the GetUriCookieContainer method that returns you a CookieContainer that can be used for subsequent call with WebRequest object.

[DllImport("wininet.dll", SetLastError = true)]
    public static extern bool InternetGetCookieEx(
        string url, 
        string cookieName, 
        StringBuilder cookieData, 
        ref int size,
        Int32  dwFlags,
        IntPtr  lpReserved);

    private const Int32 InternetCookieHttponly = 0x2000;

/// <summary>
/// Gets the URI cookie container.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns></returns>
public static CookieContainer GetUriCookieContainer(Uri uri)
{
    CookieContainer cookies = null;
    // Determine the size of the cookie
    int datasize = 8192 * 16;
    StringBuilder cookieData = new StringBuilder(datasize);
    if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
    {
        if (datasize < 0)
            return null;
        // Allocate stringbuilder large enough to hold the cookie
        cookieData = new StringBuilder(datasize);
        if (!InternetGetCookieEx(
            uri.ToString(),
            null, cookieData, 
            ref datasize, 
            InternetCookieHttponly, 
            IntPtr.Zero))
            return null;
    }
    if (cookieData.Length > 0)
    {
        cookies = new CookieContainer();
        cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
    }
    return cookies;
}