You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将带Cookie认证的HttpWebRequest转换为UnityWebRequest遇阻

问题:UnityWebRequest无法正确携带CSRF Cookie完成认证

我需要与服务器进行认证,该服务器会通过一系列重定向设置CSRF Cookie,后续所有请求还需携带oauth2 Cookie。目前已能通过HttpWebRequest获取所有Cookie并完成认证,但为了利用协程避免阻塞游戏主循环,希望将其转换为UnityWebRequest。

已能在HttpWebRequest和UnityWebRequest中成功获取CSRF Cookie,但使用UnityWebRequest登录时,无法正确发送该CSRF Cookie,导致服务器无法完成认证,也无法返回认证Cookie。

可行的HttpWebRequest代码

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();

这段代码可成功完成认证,服务器会返回认证Cookie。

改写后的UnityWebRequest代码

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();

服务器未正确接收Cookie,认证失败,无法返回认证Cookie。

核心问题在于如何将request.CookieContainer.Add(csrf);转换为UnityWebRequest的写法,尝试通过设置Cookie请求头实现但未成功。Unity文档显示UnityWebRequest有内部Cookie引擎,但该引擎完全不透明,无法查看内容。

内容的提问来源于stack exchange,提问作者YMDW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:36:24