Alamofire https自签名证书验证

Alamofire,swift语言中,使用最广的网络请求框架,是AFNetworking的swift版本,AF其实就是Alamofire的缩写,swift下叫回这个名字,也算是回归本初了。

关于HTTPS的证书

图片来自网络

一般我们拿到后台人员导出的证书,会用到两个,一个是后缀名为cer的包含公钥的CA证书,用来让客户端对服务器进行验证;一个是后缀名为p12的客户端证书,用来让服务器对客户端进行验证。我们的电脑浏览器想要访问服务器的话,直接安装客户端的p12证书就可以了,手动选择信任服务器,浏览器会报不安全的警告。这里我们也能想到,我们的app在验证的过程中,类似的也可以选择双向验证或者忽略对服务器证书验证的单项验证。

Alamofire验证证书

Alamofire将对https证书的验证放在SessionManager.delegate.sessionDidReceiveChallenge这个block里进行,所以我们给这个block赋值做验证:

//
//  HTTPSManager.swift
//  Test
//
//  Created by Fxxx on 2018/9/30.
//  Copyright © 2018 Aaron Feng. All rights reserved.
//

import UIKit
import Alamofire

class HTTPSManager: NSObject {
    
   func setAlamofireHttps() {
        
        SessionManager.default.delegate.sessionDidReceiveChallenge = { (session: URLSession, challenge: URLAuthenticationChallenge) in
            
            let method = challenge.protectionSpace.authenticationMethod
            
            if method == NSURLAuthenticationMethodServerTrust {
                
                //验证服务器,直接信任或者验证证书二选一,推荐验证证书,更安全
                return HTTPSManager.trustServerWithCer(challenge: challenge)
//                return HTTPSManager.trustServer(challenge: challenge)
                
            } else if method == NSURLAuthenticationMethodClientCertificate {
                
                //认证客户端证书
                return HTTPSManager.sendClientCer()
                
            } else {
                
                //其他情况,不通过验证
                return (.cancelAuthenticationChallenge, nil)
                
            }
            
        }
        
    }
    
    //不做任何验证,直接信任服务器
    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)
        
    }
    
    //发送客户端证书交由服务器验证
    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)
        
    }
    
}

在程序启动进行网络请求之前,调用一次setAlamofireHttps方法就好了。

image.png

PS:这里解释一下为什么不把setAlamofireHttps方法设置为静态,因为这个方法实际上是在执行一个block的赋值操作,只会被调用一次,static的生命周期是从整个程序运行开始到结束,所以除了会被频繁使用的属性或者方法,一般要谨慎使用static避免不必要的内存浪费,其他几个方法是每次网络请求都会调用,所以设置成静态比较合理。
整个类里既有静态的类方法也有实例方法,看着别扭,那有人会问,可不可以把所有方法都设置成实例方法,可以是可以,但是由于setAlamofireHttps赋值的block中调用了后续的几个方法,会持有self,这个block又是属于SessionManager.default这个单例的引用链,所以你创建的这个HTTPSManager这个实例对象会被一直持有无法释放,造成浪费。
所以综合看来,这种混合方式性能最优。

欢迎更正错误和交流,回复评论和私信皆可 😊