- Home /
Cookie not correctly set in UnityWebRequest in 2018.3
It seems that Unity has changed the implementation of how UnityWebRequest handles cookies, and it's not documented anywhere.
I have a RESTful API (written in Django), which has CSRF protection. And I have an Unity app that uses UnityWebRequest to POST things to the RESTful API.
Because of the CSRF protection, I need to pass in CSRF token for each request; the token came from response headers.
In a normal browser, browser handles the Set-Cookie header, so you don't have to manually set it; however, it is a know bug in UnityWebRequest that it does not set the Cookie header correctly, so I had to do some weird hack to set it manually, such as following (and this code works well in 2018.2):
IEnumerator Login()
{
string url = baseURL + "/accounts/login/";
WWWForm form = new WWWForm();
form.AddField("username", "username");
form.AddField("password", "helloworld");
using (UnityWebRequest www = UnityWebRequest.Post(url, form))
{
www.SetRequestHeader("X-CSRFToken", csrftoken);
www.SetRequestHeader("Cookie", string.Format("csrftoken={0}", csrftoken));
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
string cookies = www.GetResponseHeader("Set-Cookie");
sessionID = GetCookie(cookies, "sessionid");
csrftoken = GetCookie(cookies, "csrftoken");
}
}
}
Now I'm upgrading to 2018.3. I haven't changed any code on serverside, but now I'm getting all these 403 errors saying CSRF Token not matching.
At first it seems like Unity finally "fixed the bug": to make it behave like a normal browser and handles cookies automatically. So I tried getting rid of
www.SetRequestHeader("X-CSRFToken", csrftoken);
www.SetRequestHeader("Cookie", string.Format("csrftoken={0}", csrftoken));
But then the serverside either does not get cookie in request headers at all, or the request header contains outdated token.
Does anyone know how to fix this? Huge thanks in advance.
Answer by booferei · Mar 18, 2019 at 10:11 AM
Apparently Unity 2018.3 introduced a behavior change to UnityWebRequest - cookies are set automatically. So the solution to our problem is to not set the "Cookie" header (#if UNITY_2018_3_OR_NEWER).
Your answer
Follow this Question
Related Questions
save cookie after login and use it for login again 0 Answers
System cookies login application?,Cookie systeme login FPS Game 0 Answers
Workaround for SET-COOKIE bug in www.responseHeaders? 2 Answers
Saving and Fetching Cookies from UnityWebRequest 0 Answers
Access browser cookies from Web Player 2 Answers