Search Unity

Cookies, CORS and the Set-Cookie Header

Discussion in 'Web' started by ilPinguino, Dec 3, 2018.

  1. ilPinguino

    ilPinguino

    Joined:
    Dec 29, 2016
    Posts:
    1
    Hi,

    I can't get cookies working in my Unity WebGL build with a simple PHP backend.
    What I want to achieve is a Login that sends a POST request with username and password to the server, receives a session cookie and sets it in the PlayerPrefs.
    If at the start of the application, said session ID is present in the playerPrefs, it's sent to the server again.

    I set the following CORS headers on the server side:

    Access-Control-Allow-Origin →*
    Access-Control-Expose-Headers →Set-Cookie, Cookie
    Access-Control-Allow-Credentials →true

    which, when testing with Postman, are returned - however, no headers other than pragma, content-type, cache-control and expires are returned in Unity WebGL. No CORS errors are logged.

    Even more annoyingly, I can't reproduce it in the Editor - it works there, the cookie can be received, persisted using PlayerPrefs and sent on restart. Both the client side and the server side code are correct as it seems, they just fail to implement some part of the CORS standards.

    When I attempt to override the persisting and just send a valid session ID by hand, an InvalidOperationException is raised (Cannot override system-specified headers) when attempting this:

    user_check.SetRequestHeader("Cookie", PlayerPrefs.GetString("cookie"));

    I'm getting the feeling that I'm working around a present, more high-level mechanism here, but I can't find anything in the documentation. I don't really want to do it with JS code on the page as I aim for as little platform-specific code as possible.

    In case it's relevant, the server is using a HTTPS cert from LetsEncrypt. Whether the game is loaded locally or from the same server does not make a change, the code is using a HTTPS connection.

    As this needs to get done now(I'm already behind schedule), I'll work around it using a randomly generated API key that's linked to a user account on login - but for future reference, how do I work with (or at least around) CORS in Unity properly?

    Most of the threads I found were the result of improperly implementing CORS, however I think that these headers look properly implemented and the fact that no CORS errors are logged anywhere supports this assumption.

    Thanks a lot.