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)
        
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339