Alamofire進(jìn)行Https網(wǎng)絡(luò)請(qǐng)求自簽名證書(shū)

主要針對(duì)使用Alamofire進(jìn)行Https網(wǎng)絡(luò)請(qǐng)求

Alamofire 通過(guò)SessionManager.delegate.sessionDidReceiveChallenge 這個(gè)block來(lái)驗(yàn)證證書(shū), block中會(huì)將sessionchallenge 作為參數(shù)傳遞, 用戶通過(guò)其中的信息進(jìn)行判定, 返回URLSession.AuthChallengeDispositionURLCredentialAlamoFire處理

  • URLSession.AuthChallengeDisposition(認(rèn)證的意向, 枚舉值):
     //Use the specified credential, which may be nil
     //使用具體的證書(shū)
     case useCredential
     
     //Use the default handling for the challenge as though this delegate method were not implemented. The provided credential parameter is ignored
     //使用默認(rèn)的操作,如同沒(méi)有實(shí)現(xiàn)這個(gè)代理方法
     case performDefaultHandling
     
     //Cancel the entire request. The provided credential parameter is ignored
     //取消認(rèn)證
     case cancelAuthenticationChallenge
     
     //Reject this challenge, and call the authentication delegate method again with the next authentication protection space. The provided credential parameter is ignored
     //拒絕認(rèn)證, 但是會(huì)重新調(diào)用認(rèn)證的代理方法
     case rejectProtectionSpace
    ```
 - `URLCredential`(證書(shū)管理類):
   ```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
     //證書(shū)的類型由URLCredential的分類的實(shí)例化方法確定
     
     //represent an internet password credential
     //相當(dāng)于賬號(hào)密碼認(rèn)證
     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
     //客戶端證書(shū) 存在本地客戶端(獲取本地P12證書(shū), 用于客戶端認(rèn)證)
     public init(identity: SecIdentity, certificates certArray: [Any]?, persistence: URLCredential.Persistence)
     
     //specifies that the specified trust has been accepted
     //具體的trust生成的證書(shū)(用于獲取遠(yuǎn)端證書(shū)與本地cer證書(shū)對(duì)比的雙向認(rèn)證)
     public init(trust: SecTrust)
  • AlamoFire的處理方式
//默認(rèn)處理方式
    var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
    var credential: URLCredential?

    if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
        //使用自定義的簽名方式
        (disposition, credential) = sessionDidReceiveChallenge(session, challenge)
        
    } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        
        //認(rèn)證服務(wù)器證書(shū)
        let host = challenge.protectionSpace.host
        
        if
            let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
            let serverTrust = challenge.protectionSpace.serverTrust
        {
            //session對(duì)對(duì)應(yīng)的host有相應(yīng)的Policy alamofire默認(rèn)下session.serverTrustPolicyManager就為nil
            if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
                //認(rèn)證
                disposition = .useCredential
                credential = URLCredential(trust: serverTrust)
            } else {
                //取消
                disposition = .cancelAuthenticationChallenge
            }
        }
    }

認(rèn)證過(guò)程

  • 自簽名host認(rèn)證
//定義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)
    }
  • 雙向認(rèn)證
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)
    }
  • 客戶端認(rèn)證
class func clientTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        let disposition = URLSession.AuthChallengeDisposition.useCredential
        var credential: URLCredential?
        
        //獲取項(xiàng)目中P12證書(shū)文件的路徑
        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"] //客戶端證書(shū)密碼
        
        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)
    }

配置認(rèn)證

class func alamofireCertificateTrust(session: URLSession, challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        
        let method = challenge.protectionSpace.authenticationMethod
        
        //認(rèn)證服務(wù)器證書(shū)
        //SecTrustRef validation required.  Applies to any protocol.
        if method == NSURLAuthenticationMethodServerTrust {
            
            //二選一
            //雙向認(rèn)證 (需要cer)
            //return self.serverTrust(session: session, challenge: challenge)
            
            //host認(rèn)證 (這里不使用服務(wù)器證書(shū)認(rèn)證,只需自定義的幾個(gè)host即可信任)
            return self.selfSignedTrust(session: session, challenge: challenge)
            
        }
            
        //認(rèn)證客戶端證書(shū)
        //SSL Client certificate.  Applies to any protocol.
        else if method == NSURLAuthenticationMethodClientCertificate {
            
            return self.clientTrust(session: session, challenge: challenge);
            
        }
            
            // 其它情況(不接受認(rèn)證)
        else {
            
            return (.cancelAuthenticationChallenge, nil)
            
        }
    }

使用同參數(shù)同返回值的方法名給sessionDidReceiveChallenge傳值

Alamofire.SessionManager(configuration: configuration).delegate.sessionDidReceiveChallenge = CertificateTrustUtil.alamofireCertificateTrust
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容