我有一个带有自签名证书的 HTTP REST 服务器。我想使用 alamofire 从 iOS Swift 应用程序与该服务器通信。我目前的代码是:
```
let Almgr : Alamofire.SessionManager = {
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"localhost": .disableEvaluation
]
// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let man = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
return man
}()
Almgr.request(url, method: .post, parameters: params).responseJSON {
response in
if response.result.isSuccess {
print("Success")
} else {
print("Failure")
}
}
使用上面的代码片段,当我尝试进行 http 调用 Almgr.request
时,我总是遇到错误。错误信息是:
2017-12-30 18:24:20.114486+0530 myApp[58036:2721102] ATS failed system trust
2017-12-30 18:24:20.114625+0530 myApp[58036:2721102] System Trust failed for [1:0x600000178a80]
2017-12-30 18:24:20.114814+0530 myApp[58036:2721102] TIC SSL Trust Error [1:0x600000178a80]: 3:0
2017-12-30 18:24:20.115142+0530 myApp[58036:2721102] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-12-30 18:24:20.115274+0530 myApp[58036:2721102] Task <4E3D9E88-B9CE-48C4-850C-5A3E7C9A6A72>.<1> HTTP load failed (error code: -1200 [3:-9802])
2017-12-30 18:24:20.115469+0530 myApp[58036:2721231] Task <4E3D9E88-B9CE-48C4-850C-5A3E7C9A6A72>.<1> finished with error - code: -1200
知道如何解决这个问题吗?如果 url 是端口 8000 上的 localhost
,我不希望进行任何检查。我什至尝试将端口添加到 serverTrustPolicies
定义,但这没有任何区别我仍然得到错误。有什么帮助吗?
更新:我认为我的问题与 https://developer.apple.com/library/content/qa/qa1948/_index.html 有关但还没有找到解决方法。
最佳答案
1.
您修改服务器信任策略的方法应该在提供端口时起作用。另见 this post .也许您正在使用模拟器测试您的应用程序并尝试连接到同一台机器上的 Web 服务器?这可能会导致各种连接问题(或者您为什么要尝试连接到本地主机?)。
2.
您应该永远不要设置NSAllowsLocalNetworking
或类似的参数。它破坏了 SSL,你永远不知道会发生什么,即使在本地网络中也是如此。如果绝对必要,您应该只对单个主机和端口进行异常(exception)处理,如上所述。
3.
您永远不应该使用自签名证书,因为这也会破坏 SSL。使用 Let's Encrypt 很容易获得有效证书.但是,在某些情况下,无法获得有效证书。然后,您应该创建自己的证书颁发机构并将 CA 根证书导出到您的设备。这样,您也可以仅针对一个特定主机进行异常(exception)处理。
请注意,安全性在所有应用程序中都至关重要。请仅在您确切知道自己在做什么时才异常(exception)。
关于ios - 自签名本地证书上的 alamofire SSL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48034193/