CookieContainer’s cookies not being sent

Consider the following scenario:

You have a web service that you want to access with a  login url like this: http://subdomain.domain/login.php?checklogin=true, that sets a cookie after a succesful login, using Set-Cookie header without a path. Further you want to access a page like http://subdomain.domain/someservice.php.

Now with .NET you would do something like

CookieContainer cookies = new CookieContainer();

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://subdomain.domain/login.php?checklogin=true"));

request.CookieContainer = cookies;

.....

HttpWebRequest resource_request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://subdomain.domain/someservice.php"));

resource_request.CookieContainer = cookies;

Now on the second request you’ll see that your cookies are not being sent. That’s because the path for the cookies sent in the login page get the path of the original Uri which is “http://subdomain.domain/login.php”. One of the possible fixes would be calling the following function after the login request:

public static void AbsoluteCookies(ref CookieContainer cookie_container, Uri uri)
{
CookieCollection cookies = cookie_container.GetCookies(uri);

foreach (Cookie cookie in cookies)
{
cookie.Path = "/";
cookie_container.Add(cookie);
}

}

 

The above will become:

CookieContainer cookies = new CookieContainer();

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://subdomain.domain/login.php?checklogin=true"));

request.CookieContainer = cookies;

AbsoluteCookies(ref cookies, request.RequestURI);

.....

HttpWebRequest resource_request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://subdomain.domain/someservice.php"));

resource_request.CookieContainer = cookies;

Now the second request should get the cookies that were set in the initial request(login page).