swift Https單向繫結

weixin_34120274發表於2017-09-04

網上找了那麼多,基本都是來源於同一出處的,正所謂天下文章一大抄,你抄我來我抄你!

  • 基於Alamofire的https單向認證,不需要匯入證書
func authentication() {
        let manager = Alamofire.SessionManager.default
        manager.delegate.sessionDidReceiveChallenge = { session, challenge in
            var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
            var credential: URLCredential?
            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
                disposition = URLSession.AuthChallengeDisposition.useCredential
                credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            } else {
                if challenge.previousFailureCount > 0 {
                    disposition = .cancelAuthenticationChallenge
                } else {
                    credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
                    if credential != nil {
                        disposition = .useCredential
                    }
                }
            }
            return (disposition, credential)
        }
    }
  • 如果專案使用了Moya+Alamofire的網路請求模式,如果網路請求不會走上面的認證方法,
    那麼有可能是Moyaprovider預設的SessionManager和上面方法中指定的manager不一致,
    需要重新為provider指定manager
let provider = MoyaProvider<JMTAPIManager>(manager: Alamofire.SessionManager.default/*, plugins: [NetworkLoggerPlugin(verbose: true)]*/)

相關文章