WWW request with cookie header problem

Platform: Windows
Unity version: latest

We’re trying to use a www object with cookie headers for persistent session data when connecting to our server but to no avail. Currently, we are doing something like this:

  1. Make the first web request with a WWW object, using a WWWForms object to set the POST variables (username and password). Once complete, we retrieve the cookie from the www object’s response headers with the key “SET-COOKIE” and add it to our (empty) <string, string> dictionary. This works fine, the cookie is valid (as tested against logging in using a browser, checking things server side and client side in Chrome).
    WWWForm form = new WWWForm();
    form.AddField("username", username);
    form.AddField("password", password);

    WWW w = new WWW(urlLogin, form);
    yield return w;
   
    if (!string.IsNullOrEmpty(w.error))
    {
        // error handling
    }
    else
    {
        // cookieHeader is a Dictionary<string, string>
        cookieHeader.Add("Cookie", w.responseHeaders["SET-COOKIE"]);
       
        // stuff happens...
    }
  1. We make another request to retrieve data, using a www object with no POST variables but using a cookie header. What should happen is that the server should read the cookie data from the header, pull the appropriate session information and handle our request as usual. When testing using in the browser, this works fine, but when making the request using the WWW object in Unity, the server doesn’t receive the cookie header:
    WWW w = new WWW(urlSomeService, new byte[] { 0 }, cookieHeader);

    yield return w;

    if (!string.IsNullOrEmpty(w.error))
    {
        // error handling
    }
    else
    {
        // response received from server but no data in cookie header to complete request
    }

Any suggestions as to what we’re doing wrong?

Did you guys figure it out? i’m having the same problem :confused:

Try printing out the cookie header.
It’s likely that Set-Cookie header in response has extra information about the cookie and you should not send that information in the Cookie header of your next request. Usually you should only send the name=value part of it.

This is how we got our session id from the received Set-Cookie

private const string COOKIE_HEADER_KEY = "SET-COOKIE";
private const string COOKIE_PHPSESSION = "PHPSESSID";

string cookieString = www.responseHeaders[COOKIE_HEADER_KEY];

Regex regex = new Regex(COOKIE_PHPSESSION + "=(.*?);");
string sessionId = regex.Match(cookieString).Value;
sessionId = sessionId.Replace(";", string.Empty);
string finalSessionId = sessionId.Substring(sessionId.Length - (sessionId.Length - COOKIE_PHPSESSION.Length) + 1);

Better print it out and check that you actually parse it correctly.