【发布时间】:2020-01-30 05:32:50
【问题描述】:
我正在开发一个 Unity 项目,该项目依赖于从我在公共网络服务器上设置的网络 API 获取数据。服务器当前设置为自签名 ssl,并要求客户端发送证书才能读取数据,如果客户端发送证书失败,网站将返回 “403 禁止”。
我已经在浏览器和邮递员中对此进行了测试,一切正常。 我还在一个纯视觉工作室项目中测试了完全相同的功能,它就像一个魅力。
但是,当我在 Unity 中尝试此功能时,我遇到了 WebException “请求超时 "。
我目前的做法是通过 WebClient,并使用 WebRequest 的覆盖方法:
private void Connect()
{
ServicePointManager.CheckCertificateRevocationList = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback += ignoreCertCallback;
ServicePointManager.Expect100Continue = true;
using (var wc = new CertificateWebClient())
{
try
{
var responseBytes = wc.DownloadString(url);
Debug.Log(responseBytes);
Debug.Log(wc.ResponseHeaders);
}
catch (WebException e)
{
Debug.Log(e.ToString());
}
}
}
WebRequest 的覆盖:
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
X509Certificate2 certificate = new X509Certificate2(@"C:\temp\ClientCert.pfx", "password");
request.ServerCertificateValidationCallback = delegate (System.Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
{
return true;
};
Debug.Log(request.RequestUri);
(request as HttpWebRequest).ClientCertificates.Add(certificate);
request.Timeout = 2000;
return request;
}
需要注意的重要一点是,我在 Unity 中使用“client.badssl.com”及其证书尝试了完全相同的功能,这也很有效,在没有发送证书时返回正确的错误代码和一切,如果我在我的网站上关闭客户认证,一切都会像魅力一样运作......
据我了解,这可能是 Mono 的问题,因为证书是自签名的,而不是来自经过验证的 CA……但我无法找到解决方法……所以任何帮助会很棒
【问题讨论】:
-
您应该改用
UnityWebRequest。然后你可以关注my answer here -
我不能使用 UnityWebRequest,因为我需要实际发送客户端证书,据我所知,UnityWebRequest 无法做到这一点。我已经让它接受实际的服务器,如果我关闭要求客户端证书一切正常......所以实际问题必须与客户端认证有关
标签: unity3d ssl mono webclient