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<JMTAPIManager>(manager: Alamofire.SessionManager.default/*, plugins: [NetworkLoggerPlugin(verbose: true)]*/)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文章摘自Moya官方文档 Targets Moya的使用始于定义一个target——典型的是定义一个符合Targe...
    Jt_Self阅读 16,241评论 0 27
  • 原文地址:https://github.com/Moya/Moya/tree/master/docs参考文章:ht...
    狂奔的兔子阅读 3,390评论 0 53
  • Alamofire的基本用法 1.请求 这是一个最简单的请求,这个请求即不需要参数,也不需要接收数据。接下来我们翻...
    水落斜阳阅读 3,258评论 0 16
  • Alamofire 是一款 Swift 写的 HTTP 网络请求库 前言 本篇内容为 Alamofire 官方 R...
    zongmumask阅读 20,965评论 6 66
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,227评论 25 708