We recently created a webGL game that is up on our game site right now. Like any webGL game that interacts with a back-end server, we wanted to be able to save data and know who was requesting any information from us and be able to save a character's progress.
During development, we worked extensively within the Unity Editor and we were able to initiate a web session by logging in. Every call to our server would transmit our cookie information and our user account would know who we were. Even as we tested against another web browser client, sessions would persist and testing would go well.
The real issue started when we played our game exclusively through a web browser. We started getting CORS errors and scrambled to find the appropriate headers to set on the web servers. Then we started viewing something peculiar. UnityWebRequest objects were not saving our cookie information due to security restrictions; both self-imposed and those from the browser.
The work around was to utilize a ".jslib" file and interface with the web browser directly. A Unity webGL build apparently uses the host web browser's cookie store. So as a work around, we pieced together from various StackOverflow and Unity Forum posts, to come up with the following. This is code from a ".jslib" for our project:
JSLogin: function (url,formdata){
var jsURL = Pointer_stringify(url);
var jsFormData = Pointer_stringify(formdata);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(xhttp.responseText);
}
};
xhttp.open("POST",jsURL,true);
xhttp.withCredentials = true;
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send(jsFormData);
},
I made the call from a Monobehaviour class:
using System.Runtime.InteropServices;
//Declare below inside the class body
[DllImport("__Internal")]
private static extern void JSLogin(string url,string formdata);
The above, since the call was being made through the web browser by using an XMLHttpRequest object, was enough to write the cookie to the cookie store. Every other web request made after login was able to utilize the UnityWebRequest object without any issues and our server session was persisted.
(Website has been shut down)
Hi !
Thanks for this very interesting article. Could you tell me how you managed to get the cookie after login?