【问题标题】:UnityWebRequest WebGL Missing Cookie Response HeaderUnityWebRequest WebGL 缺少 Cookie 响应标头
【发布时间】:2022-07-20 14:57:49
【问题描述】:

我正在使用 Unity 将包含用户名和密码的登录表单数据发布到端点。我收到包含预期凭据(作为会话 cookie)的成功响应,并且在 Unity 编辑器中测试时成功完成后续通信。

当我将项目部署和构建为 WebGL 时,我没有从我的登录请求中收到“Set-Cookie”标头。这会导致所有后续通信都失败未经授权的 401。

  • WebGL 日志中的日志返回成功响应。
  • 在浏览器中检查时,我看到成功响应返回了预期的会话 cookie 凭据,标题为“Set-Cookie”。
  • 但 UnityWebRequest 在查询“Set-Cookie”响应标头时返回 null。一些标题仍然存在,但大多数似乎已被剥离。
  • WebGL 构建从启用 https 的服务器部署和播放 - 这是与登录服务器不同的服务器

我认为在响应返回到我的程序之前有一些安全性(CORS?)剥离这些凭据。允许凭据和 Origin 响应标头显示正确。 'Set-Cookie' 响应头格式为:

Set-Cookie: SESSION=tvohm-example-session; Path=/tvohm-example-path/; Secure; HttpOnly; SameSite=Lax

缩小:

IEnumerator LogInCoroutine()
{
    using var request = new UnityWebRequest("https://tvohm-example-url.com/login")
    {
        method = UnityWebRequest.kHttpVerbPOST,
        uploadHandler = new UploadHandlerRaw(UnityWebRequest.SerializeSimpleForm(new Dictionary<string, string>()
            {
                { "username", "tvohm" },
                { "password", "ilovestackoverflow" }
            }))
    };
    request.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    yield return request.SendWebRequest();
    if (request.result == UnityWebRequest.Result.Success)
    {
        Debug.Log(request.GetResponseHeader("Set-Cookie"));
        // Editor returns expected session cookie
        // WebGl returns null
    }
}

调用:

StartCoroutine(LogInCoroutine());

【问题讨论】:

    标签: c# unity3d cookies http-headers webgl


    【解决方案1】:

    您无法在 javascript 中读取或写入 "Set-Cookie" 标头,因为浏览器会将其隐藏起来,因为它是一个禁止标头。 https://fetch.spec.whatwg.org/#forbidden-header-name 浏览器将为您处理 cookie(因此从您的响应标头中裁剪该标头,以便您无法访问它)并在您添加 Request-header "withCredentials=true" 时自动在您的请求中添加 Cookie 标头。这一措施提高了安全性。

    这就是我目前陷入困境的地方,您可以在此处阅读: https://forum.unity.com/threads/cant-set-cookie-header-in-webgl-with-unitywebrequest.425981/#post-8291783

    如果您只需要访问 Set-Cookie 响应,那么您的服务器应该改为在响应中发送它或在另一个不受限制的标头名称中发送。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2019-06-01
      • 2019-02-25
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多