swift Https单向绑定

网上找了那么多,基本都是来源于同一出处的,正所谓天下文章一大抄,你抄我来我抄你!

  • 基于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(manager: Alamofire.SessionManager.default/*, plugins: [NetworkLoggerPlugin(verbose: true)]*/)

你可能感兴趣的:(swift Https单向绑定)