CookieContainer, HttpWebRequest and Secure Cookies

287 words.

I ran across a troublesome problem that took several evenings to debug.  I couldn’t find a solution with Google so maybe somebody else will benefit from this.

My app sent an HTTP GET to a secure site using an HttpWebRequest and a CookieContainer (to capture the site’s cookies).  Two cookies were returned in the response header, one of which was marked by the server as “Secure.”  Both cookies were in the CookieContainer (the Count was 2 and they were both returned by GetCookies(url)).  However, I subsequently sent an HTTP POST using the same CookieContainer to the same site (still https), but HttpWebRequest did not place the secure cookie into the POST header.

This might be by design, a misunderstanding on my part, or a problem with the site’s cookies, but in any case it was not working.  To get around the problem, I had to manually add the missing cookie to the CookieContainer before calling HttpWebRequest.GetResponse.  Only after doing that was the cookie added to the outgoing request header and subsequently sent to the server.  Something like this:

CookieContainer cookieContainer = new CookieContainer();

 

HttpWebResponse response = DoHttpGet( cookieContainer );

 

// Manually add the missing cookie.

Cookie cookie = new Cookie( "Name", response.Cookies["Name"].Value );

cookie.Secure = true;

cookie.Domain = "www.domain.com";

cookieContainer.Add( cookie );

 

DoHttpPost( cookieContainer );

Alternatively, I found that this worked also:

HttpWebResponse response = DoHttpGet( cookieContainer );

// Alternative to the above.

cookieContainer.Add( new Uri( "https://www.domain.com" ), response.Cookies );

DoHttpPost( cookieContainer );

However, a plain cookieContainer.Add( response.Cookies) — a frequently-referenced Google solution - did not work.

HttpWebResponse response = DoHttpGet( cookieContainer );

// This did not work.

cookieContainer.Add( response.Cookies );

DoHttpPost( cookieContainer );

By the way, Fiddler was invaluable in debugging this issue.

Related

This page is a static archival copy of what was originally a WordPress post. It was converted from HTML to Markdown format before being built by Hugo. There may be formatting problems that I haven't addressed yet. There may be problems with missing or mangled images that I haven't fixed yet. There may have been comments on the original post, which I have archived, but I haven't quite worked out how to show them on the new site.

Sorry, new comments are disabled on older posts. This helps reduce spam. Active commenting almost always occurs within a day or two of new posts.