Alamofire证书固定不会阻止请求

时间:2017-06-20 11:38:54

标签: ios swift ssl ssl-certificate alamofire

我对Alamofire中的SSL Pinning有些麻烦。我已经检查了所有可以找到的文件,但我无法处理它。我可能会弄错。

目前,我正在研究一个例子 https://github.com/antekarin/ios-ssl-pinning

我将它转换为swift 3并将豆荚更新为最新版本的Alamofire。

说清楚;该项目是使用" github.com.cer"证书,因为我定义了域名(如下所示),我希望在去#34; https://github.com"当我进入(例如)" https://twitter.com"时失败。但在每种情况下,我的请求都会返回一些值,并且不会阻止其他请求。

self.serverTrustPolicies = [
  "github.com": self.serverTrustPolicy!
]

代码:

    let githubCert = "github.com"
    let corruptedCert = "corrupted"

    var urlSession: Foundation.URLSession!
    var serverTrustPolicy: ServerTrustPolicy!
    var serverTrustPolicies: [String: ServerTrustPolicy]!
    var afManager: SessionManager!

    var isSimulatingCertificateCorruption = false

    override func viewDidLoad() {
        super.viewDidLoad()

        self.configureAlamoFireSSLPinning()
        self.configureURLSession()

        self.activityIndicator.hidesWhenStopped = true
    }

    // MARK: SSL Config

    func configureAlamoFireSSLPinning() {
        let pathToCert = Bundle.main.path(forResource: githubCert, ofType: "cer")
        let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!

        self.serverTrustPolicy = ServerTrustPolicy.pinCertificates(
            certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
            validateCertificateChain: true,
            validateHost: true
        )

        self.serverTrustPolicies = [
            "github.com": self.serverTrustPolicy!
        ]

        self.afManager = SessionManager(
            configuration: URLSessionConfiguration.default,
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: self.serverTrustPolicies)
        )
    }


    // MARK: Button actions

    @IBAction func alamoFireRequestHandler(_ sender: UIButton) {
        self.activityIndicator.startAnimating()
        if let urlText = self.urlTextField.text {

            self.afManager.request(urlText).responseString { response in

                guard let data = response.data, response.error == nil else {
                    self.responseTextView.text = response.error.debugDescription
                    self.responseTextView.textColor = UIColor.red
                    return
                }

                self.responseTextView.text = String(data: data, encoding: String.Encoding.utf8)!
                self.responseTextView.textColor = UIColor.black
            }


        }
    }

0 个答案:

没有答案