I'm authenticating with a server that, through a series of redirects sets a CSRF cookie. I also get a oauth2 cookie that I need to include for all subsequent queries.
I'm able to obtain all the cookies and authenticate using HttpWebRequest
- but I'd like to convert this to use UnityWebRequest
so I can make use of Coroutines to not block the main game loop.
I am able to obtain the CSRF cookie in both HttpWebRequest
and UnityWebRequest
- ✅
The issue I'm having is how to send this CSRF cookie using UnityWebRequest
when trying to login.
My HttpWebRequest
looks like this...
ServicePointManager.ServerCertificateValidationCallback = TrustCertificate;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = method;
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
Cookie csrf = new Cookie("_oauth2_proxy_csrf", CSRF_COOKIE, "/", server_ip);
request.CookieContainer.Add(csrf);
request.Proxy = null;
if (method == "POST")
{
NameValueCollection nvc = new NameValueCollection();
nvc.Add("login", username);
nvc.Add("password", password);
StringBuilder postVars = new StringBuilder();
foreach (string key in nvc)
postVars.AppendFormat("{0}={1}&", key, nvc[key]);
postVars.Length -= 1; // clip off the remaining &
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(postVars.ToString());
}
}
var response = (HttpWebResponse)request.GetResponse();
This works successfully, the server authenticates me and provides an authentication cookie - ✅
Now, my translated UnityWebRequest
code looks like this...
List<IMultipartFormSection> post_data = new List<IMultipartFormSection>();
post_data.Add(new MultipartFormDataSection("login", username));
post_data.Add(new MultipartFormDataSection("password", password));
UnityWebRequest request = UnityWebRequest.Post(url, post_data);
request.uploadHandler.contentType = "application/x-www-form-urlencoded";
request.certificateHandler = new ForceAcceptAll();
request.redirectLimit = 1;
request.SetRequestHeader("_oauth2_proxy_csrf", CSRF_COOKIE);
string cookie = string.Format("{0}={1}", "_oauth2_proxy_csrf", CSRF_COOKIE);
request.SetRequestHeader("Cookie", cookie);
yield return request.SendWebRequest();
The server doesn't appear to be receiving the cookie correctly. It won't authenticate correctly and doesn't provide the auth cookie like it does with HttpWebResponse
I think it boils down to how to translate
request.CookieContainer.Add(csrf);
into UnityWebRequest
- ❓
which I thought would be:
string cookie = string.Format("{0}={1}", "_oauth2_proxy_csrf", CSRF_COOKIE);
request.SetRequestHeader("Cookie", cookie);
The Unity docs say that UnityWebRequest
has an internal cookie engine - but as far as I can see it completely opaque so I can't see what the contents are.