UnityWebRequest with including httpOnly cookies

Hi all,

I have an WebGL application which needs to integrate with the existing authentication system at my work which uses session cookies to authenticate requests.

I have not been able to find a way to configure Unity to enable the credentials: "include" option which is typically set on JavaScript fetch requests to instruct the browser to include cookies in the request.

From some older resources I found online, the advice stated that this was impossible to enable natively within Unity, and suggested using a 'hack' which involved overriding the XMLHttpRequest object to enable withCredentials: true by default, thus ensuring that the requests from Unity include cookies once they are converted for WebGL.

I've also learned that since version 2021.3, Unity now uses the Fetch API to make WebGL network requests. Thus, the previously suggested override hack no longer works.

What is the recommended approach for making requests from Unity that include httpOnly cookies automatically using the credentials option?

Extending on this feature is unfortunately not currently supported.

It should be possible to solve the issue by monkey patching fetch() API to inject the custom credentials.

Alternatively, you can try copying the FetchWithProgress.js file into your project as a "FetchWithProgress.prejs" file, and then modifying the implementation of fetch() there to post the custom credentials. I believe that should allow overriding the default functionality.

I'm in a similar scenario. Here's a selection of answers and blog posts that I'm looking into:


My solution:
1) create custom html template: https://docs.unity3d.com/2023.2/Documentation/Manual/webgl-templates.html
2) add this code before in index.html:

const originalfetch = fetch;
   fetch = function( url,data) {
      data = {...data, ...{credentials : "include"}};
      return originalfetch(url,data);

3) Server response settings (asp.net core):

options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax; //resend cookies only FROM this domain & subdomain

if (builder.Environment.IsDevelopment())
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always; //required if SameSite=None
    options.Cookie.SameSite = SameSiteMode.None; //resend cookies FROM any domains
if (app.Environment.IsDevelopment())
    app.UseCors(x =>
    x.AllowAnyHeader() // (!ONLY DEV)
    .AllowAnyMethod() // (!ONLY DEV)
    .AllowCredentials() //allow client (cors): set-cookie (!ONLY DEV)
    .SetIsOriginAllowed(options => true) //all origins (!ONLY DEV)
    //.AllowAnyOrigin() //not working with AllowCredentials