Alamofire进行Https网络请求自签名证书

主要针对使用Alamofire进行Https网络请求

Alamofire 通过SessionManager.delegate.sessionDidReceiveChallenge 这个block来验证证书, block中会将sessionchallenge 作为参数传递, 用户通过其中的信息进行判定, 返回URLSession.AuthChallengeDispositionURLCredentialAlamoFire处理

  • URLSession.AuthChallengeDisposition(认证的意向, 枚举值):
     //Use the specified credential, which may be nil
     //使用具体的证书
     case useCredential
     
     //Use the default handling for the challenge as though this delegate method were not implemented. The provided credential parameter is ignored
     //使用默认的操作,如同没有实现这个代理方法
     case performDefaultHandling
     
     //Cancel the entire request. The provided credential parameter is ignored
     //取消认证
     case cancelAuthenticationChallenge
     
     //Reject this challenge, and call the authentication delegate method again with the next authentication protection space. The provided credential parameter is ignored
     //拒绝认证, 但是会重新调用认证的代理方法
     case rejectProtectionSpace
    ```
 - `URLCredential`(证书管理类):
   ```swift
     //This class is an immutable object representing an authentication credential.  The actual type of the credential is determined by the constructor called in the categories declared below
     //证书的类型由URLCredential的分类的实例化方法确定
     
     //represent an internet password credential
     //相当于账号密码认证
     public init(user: String, password: String, persistence: URLCredential.Persistence)
     
     //represent a client certificate credential. Client certificates are commonly stored on the users computer in the keychain and must be presented to the server during a handshake
     //客户端证书 存在本地客户端(获取本地P12证书, 用于客户端认证)
     public init(identity: SecIdentity, certificates certArray: [Any]?, persistence: URLCredential.Persistence)
     
     //specifies that the specified trust has been accepted
     //具体的trust生成的证书(用于获取远端证书与本地cer证书对比的双向认证)
     public init(trust: SecTrust)
  • AlamoFire的处理方式
//默认处理方式
    var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
    var credential: URLCredential?

    if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
        //使用自定义的签名方式
        (disposition, credential) = sessionDidReceiveChallenge(session, challenge)
        
    } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        
        //认证服务器证书
        let host = challenge.protectionSpace.host
        
        if
            let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
            let serverTrust = challenge.protectionSpace.serverTrust
        {
            //session对对应的host有相应的Policy alamofire默认下session.serverTrustPolicyManager就为nil
            if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
                //认证
                disposition = .useCredential
                credential = URLCredential(trust: serverTrust)
            } else {
                //取消
                disposition = .cancelAuthenticationChallenge
            }
        }
    }

认证过程

  • 自签名host认证
//定义host白名单
static let selfSignedHosts = ["yue.haofenshu.com"]
class func selfSignedTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
        var credential: URLCredential?
        
        if selfSignedHosts.contains(challenge.protectionSpace.host) {
            
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            
        }
        
        return (disposition, credential)
    }
  • 双向认证
class func serverTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
        var credential: URLCredential?
        
        //grab remote certificate
        let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!
        let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
        let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
        
        //grab local certificate
        let cerPath = Bundle.main.path(forResource: "haofenshu", 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)
    }
  • 客户端认证
class func clientTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        let disposition = URLSession.AuthChallengeDisposition.useCredential
        var credential: URLCredential?
        
        //获取项目中P12证书文件的路径
        let path: String = Bundle.main.path(forResource: "haofenshu", ofType: "p12")!
        let PKCS12Data = NSData(contentsOfFile:path)!
        let key : NSString = kSecImportExportPassphrase as NSString
        let options : NSDictionary = [key : "123456"] //客户端证书密码
        
        var items: CFArray?
        let error = SecPKCS12Import(PKCS12Data, options, &items)
        
        if error == errSecSuccess {
            
            if let itemArr = items as? NSArray,
                let item = itemArr.firstObject as? Dictionary<String, AnyObject> {
                
                // grab the identity
                let identityPointer = item["identity"];
                let secIdentityRef = identityPointer as! SecIdentity
                
                // grab the trust
                // let trustPointer = item["trust"]
                // let trustRef = trustPointer as! SecTrust
                
                // grab the cert
                let chainPointer = item["chain"]
                let chainRef = chainPointer as? [Any]
                
                // persistence: Credential should be stored only for this session
                credential = URLCredential.init(identity: secIdentityRef, certificates: chainRef, persistence: URLCredential.Persistence.forSession)
                
            }
            
        }
        
        return (disposition, credential)
    }

配置认证

class func alamofireCertificateTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        let method = challenge.protectionSpace.authenticationMethod
        
        //认证服务器证书
        //SecTrustRef validation required.  Applies to any protocol.
        if method == NSURLAuthenticationMethodServerTrust {
            
            //二选一
            //双向认证 (需要cer)
            //return self.serverTrust(session: session, challenge: challenge)
            
            //host认证 (这里不使用服务器证书认证,只需自定义的几个host即可信任)
            return self.selfSignedTrust(session: session, challenge: challenge)
            
        }
            
        //认证客户端证书
        //SSL Client certificate.  Applies to any protocol.
        else if method == NSURLAuthenticationMethodClientCertificate {
            
            return self.clientTrust(session: session, challenge: challenge);
            
        }
            
            // 其它情况(不接受认证)
        else {
            
            return (.cancelAuthenticationChallenge, nil)
            
        }
    }

使用同参数同返回值的方法名给sessionDidReceiveChallenge传值

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

推荐阅读更多精彩内容