iOS Https证书验证问题全解
在调用Https地址请求数据时,我们会遇到证书验证的问题。
关于证书调用的方法。主要有两个代理
这两个方法是不同的,一个是session负责处理,一个是task负责处理,处理的方式一样,一般我们会用session来处理。
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
从委托请求凭据,以响应来自远程服务器的会话级身份验证请求。
optional func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
- When a remote server asks for client certificates or Windows NT LAN Manager (NTLM) authentication, to allow your app to provide appropriate credentials
- When a session first establishes a connection to a remote server that uses SSL or TLS, to allow your app to verify the server’s certificate chain
If you do not implement this method, the session calls its delegate’s urlSession(_:task:didReceive:completionHandler:) method instead.
翻译:
这种方法在两种情况下调用:
当远程服务器请求客户端证书或Windows NT LAN Manager (NTLM)身份验证时,允许您的应用程序提供适当的凭据
当会话首次建立到使用SSL或TLS的远程服务器的连接时,允许您的应用程序验证服务器的证书链
如果不实现此方法,则会话将调用其委托的urlSession(_:task:didReceive:completionHandler:)方法。
当sesion的代理方法未实现时,会执行下面的这种方式,如果两种方法都未实现的时候会怎么处理呢?我们下面会说到。
Requests credentials from the delegate in response to an authentication request from the
remote server.
从委托请求凭据以响应来自远程服务器的身份验证请求。
optional func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
This method handles task-level authentication challenges. The URLSessionDelegate protocol also provides a session-level authentication delegate method. The method called depends on the type of authentication challenge:
For session-level challenges—NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate, or NSURLAuthenticationMethodServerTrust—the NSURLSession object calls the session delegate’s urlSession(_:didReceive:completionHandler:) method. If your app does not provide a session delegate method, the NSURLSession object calls the task delegate’s urlSession(_:task:didReceive:completionHandler:) method to handle the challenge.
For non-session-level challenges (all others), the URLSession object calls the session delegate’s urlSession(_:task:didReceive:completionHandler:) method to handle the challenge. If your app provides a session delegate and you need to handle authentication, then you must either handle the authentication at the task level or provide a task-level handler that calls the per-session handler explicitly. The session delegate’s urlSession(_:didReceive:completionHandler:) method is not called for non-session-level challenges.
翻译:
此方法处理任务级身份验证挑战。URLSessionDelegate协议还提供了一个任务级的身份验证委托方法。所调用的方法取决于认证挑战的类型:
对于会话级别的挑战——nsurlauthenticationmethodntlm、NSURLAuthenticationMethodNegotiate、NSURLAuthenticationMethodClientCertificate或nsurlauthenticationmethodservertrust——NSURLSession对象调用会话委托的urlSession(_:didReceive:completionHandler:)方法。如果你的应用程序没有提供一个会话委托方法,NSURLSession对象会调用任务委托的urlSession(_:task:didReceive:completionHandler:)方法来处理这个挑战。
对于非会话级别的挑战(所有其他挑战),URLSession对象调用会话委托的URLSession (_:task:didReceive:completionHandler:)方法来处理该挑战。如果您的应用程序提供了一个会话委托,而您需要处理身份验证,那么您必须在任务级处理身份验证,或者提供一个显式调用每个会话处理程序的任务级处理程序。对于非会话级挑战,不会调用会话委托的urlSession(_:didReceive:completionHandler:)方法。
这两个代理方法的总结就是,如果是session级别的验证,那么可以使用任一一种方法解决。
如果是非会话级别的验证(on-session-level challenges (all others)),那么session级别不能替代task级别。
- 不同的请求验证方式
NSURLAuthenticationMethodClientCertificate
此保护空间使用客户端证书身份验证。
NSURLAuthenticationMethodNegotiate
协商在这个保护空间中使用Kerberos还是NTLM身份验证。
NSURLAuthenticationMethodNTLM
对这个保护空间使用NTLM身份验证。
NSURLAuthenticationMethodServerTrust
为这个保护空间执行服务器信任身份验证(证书验证)。
在处理会话的时候,将分为三个部分
- 验证服务器证书 NSURLAuthenticationMethodServerTrust
- 服务器验证本地 NSURLAuthenticationMethodClientCertificate
- 其他 NSURLAuthenticationMethodNTLM,NSURLAuthenticationMethodNegotiate
一般我们会用到两种,一种是我们验证服务器,一种是服务器验证客户端。
NSURLAuthenticationMethodServerTrust
如果我们验证服务器的话,可以有两种方式
- 直接验证通过
- 使用代码和证书验证
//不做任何验证,直接信任服务器
static private func trustServer(challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
let disposition = URLSession.AuthChallengeDisposition.useCredential
let credential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
return (disposition, credential)
}
//验证服务器证书
static private func trustServerWithCer(challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
//获取服务器发送过来的证书
let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
//加载本地CA证书
let cerPath = Bundle.main.path(forResource: "你本地的cer证书文件名", ofType: "cer")!
let cerUrl = URL(fileURLWithPath:cerPath)
let localCertificateData = try! Data(contentsOf: cerUrl)
if (remoteCertificateData.isEqual(localCertificateData) == true) {
//服务器证书验证通过
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: serverTrust)
} else {
//服务器证书验证失败
disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
}
return (disposition, credential)
}
NSURLAuthenticationMethodClientCertificate
//发送客户端证书交由服务器验证
static private func sendClientCer() -> (URLSession.AuthChallengeDisposition, URLCredential?) {
let disposition = URLSession.AuthChallengeDisposition.useCredential
var credential: URLCredential?
//获取项目中P12证书文件的路径
let path: String = Bundle.main.path(forResource: "你本地的p12证书文件名", ofType: "p12")!
let PKCS12Data = NSData(contentsOfFile:path)!
let key : NSString = kSecImportExportPassphrase as NSString
let options : NSDictionary = [key : "p12证书的密码"] //客户端证书密码
var items: CFArray?
let error = SecPKCS12Import(PKCS12Data, options, &items)
if error == errSecSuccess {
let itemArr = items! as Array
let item = itemArr.first!
let identityPointer = item["identity"];
let secIdentityRef = identityPointer as! SecIdentity
let chainPointer = item["chain"]
let chainRef = chainPointer as? [Any]
credential = URLCredential.init(identity: secIdentityRef, certificates: chainRef, persistence: URLCredential.Persistence.forSession)
}
return (disposition, credential)
}