ios - 如何在不将 NSAllowsArbitraryLoads 设置为 yes 的情况下处理自签名证书?

标签 ios swift ssl tvos

我是 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 的情况下执行此操作。对此有何建议?如果仅用于测试,这可以吗?

谢谢!

最佳答案

NSAllowsArbitraryLoads 不应该被使用,即使是在测试中。也许你只是忘记在生产中删除这个参数,所有的安全性都消失了。此外,最好针对具有真实证书的服务器进行测试,以检测可能的错误和安全问题。

如果您没有特殊设置,从Let's Encrypt 获取免费服务器证书应该相对容易。 .这些证书已被 Apple 设备接受,并且一切正常。

另一种可能性是创建您自己的证书颁发机构 (CA) 并将 CA 证书导出到您的设备。然后您的设备将接受此 CA 签署的所有证书。看看this post从我这里获取详细信息。

关于ios - 如何在不将 NSAllowsArbitraryLoads 设置为 yes 的情况下处理自签名证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49702590/

相关文章:

ios - iOS:IAP如何工作?

ios - 如何解决 NSURLError : The network connection was lost?

objective-c - UITabBar.appearance().barTintColor 不适用于 Xcode 中的自定义颜色

java - 检查设备是否接受证书

ios - Swift UIViewController tableView.reloadData nil 在第二次调用时换行

ios - 在 iOS 上以编程方式安装 .ipa

apache - SSLCACertificateFile 和 SSLCertificateChainFile 之间的区别

docker - 如何使用自签名证书通过 TLS 将 Docker 应用程序包推送到私有(private)注册表

ios - NSUserDefaults.standardUserDefaults().dictionaryForKey() 返回编译错误

ios - 字典 swift 4 中的保留容量是什么?