我试图通过https为我的iOS应用程序使用Web服务。 Web服务器使用自签名证书。Alamofire 4.0证书无效问题
使用Web服务时,出现错误“证书无效”。
失败:“它可以把您的机密信息处于危险之中‘错误域= NSURLErrorDomain代码= -1202’此服务器的证书无效,您可能正在连接到一个伪装成是服务器”门户网站
我知道最好的做法是在服务器端修复这个问题,以启用受信任的根CA.但是,由于这是一个临时开发环境,我们正在使用自签名证书。 由于这是ATS问题,我已经在我的info.plist中编辑了ATS,如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>devportal</key>
<dict>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
</plist>
由于NSException域不会与IP和端口号的工作,我已经创造了我等主机条目/ hosts文件的Web服务器IP和https://192.22.xx.xxx:8443/rest/login
消耗它像 https://devportal:8443/rest/login不是消耗它的我遵循关于服务器信任策略的alamofire文档,编辑了ATS以允许异常域,但没有为我解决。我已经在这个问题上花了3天时间。我错过了什么吗?有人遇到过类似的问题吗?有没有解决方案?在此先感谢
我使用almofire 4.0,Xcode 8.0。以下是我的代码。
class LoginService{
private static var Manager: Alamofire.SessionManager = {
let pathToCert = Bundle.main.path(forResource: "192.22.xx.xxx", ofType: "crt") // Downloaded this certificate and have added to my bundle
let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!
// Create the server trust policies
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"192.22.xx.xxx": .pinCertificates(
certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
validateCertificateChain: true,
validateHost: true
),
"devportal:8443": .disableEvaluation
]
// Create custom manager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
let manager = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
return manager
}()
/**
Calls the Login Web Service to authenticate the user
*/
public func login(username:String, password: String){
let parameters = [
"username": "TEST",
"password": "PASSWORD",
]
let header: HTTPHeaders = ["Accept": "application/json"]
LoginService.Manager.request("https://devportal:8443/rest/login", method: .post, parameters: parameters, encoding: JSONEncoding(options: []),headers :header).responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}
}
}
}
您的测试设备是否配置为信任自签名证书?这可以在iOS设置 - >常规 - >配置文件中验证。 –
@Rein我没有在设备上测试它,因为它没有测试准备好。我刚开始开发并在模拟器上运行它。 – CrazyDeveloper