我是swift的新手,我正在试图找出如何向具有自签名证书的服务器发送一些POST请求。我正试图点击开发服务器进行测试。这就是我实现didReceive挑战函数的方法:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let method = challenge.protectionSpace.authenticationMethod
let host = challenge.protectionSpace.host
NSLog("challenge %@ for %@", method, host)
switch (method, host) {
case (NSURLAuthenticationMethodServerTrust, "mydomain.example.com"):
let trust = challenge.protectionSpace.serverTrust!
let credential = URLCredential(trust: trust)
completionHandler(.useCredential, credential)
case (NSURLAuthenticationMethodClientCertificate, "mydomain.example.com"):
completionHandler(.performDefaultHandling, nil)
default:
completionHandler(.cancelAuthenticationChallenge, nil)
}
这就是我的Info.plist源代码使调用工作的原因:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>mydomain.example.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
我一直在研究如何在线进行此操作,看起来这可能不是最安全的方法 - 将NSAllowsArbitraryLoads设置为true会有什么风险?我尝试删除该位但后来我会收到此错误:
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made."
如果没有启用NSAllowsArbitraryLoads,我无法弄清楚是否有办法做到这一点。有什么建议吗?如果仅用于测试,这会没问题吗?
谢谢!
答案 0 :(得分:0)
NSAllowsArbitraryLoads
,即使在测试中也是如此。也许您只是忘记在生产中删除此参数,并且所有安全性都消失了。此外,最好使用真实证书对服务器进行测试,以检测可能的错误和安全问题。
如果您没有特殊设置,从Let's Encrypt获取免费服务器证书应该相对容易。这些证书被Apple设备接受,一切都会有效。
另一种可能性是创建自己的证书颁发机构(CA)并将CA证书导出到您的设备。然后,您的设备将接受此CA签署的所有证书。请查看我的this post以获取详细信息。