swift afnetworking ssl pinning

◇◆丶佛笑我妖孽 提交于 2019-12-13 19:42:14

问题


var manager: AFHTTPSessionManager

init() {
    manager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer()
    manager.responseSerializer = AFJSONResponseSerializer()

    let securityPolicy = AFSecurityPolicy(pinningMode: AFSSLPinningMode.Certificate)
    let certificatePath = NSBundle.mainBundle().pathForResource("c38acbe05a6328ee", ofType: "crt")!
    let certificateData = NSData(contentsOfFile: certificatePath)!

    securityPolicy.pinnedCertificates = [certificateData]
    securityPolicy.validatesDomainName = false
    securityPolicy.allowInvalidCertificates = false

    manager.securityPolicy = securityPolicy
}

I've been trying to get this working for some time now. Swift documentation is sparce, but I'm getting better at reading obj-c. The cert is in PEM format, I've tried that and converting to .der format. Der format blows up in init(), .PEM format blows up in evaluateServerTrust. I tried in AFNetworking 2.5.1 and upgraded to 3.0.4 - same issue. I've tried every combination of true and false for the following.

securityPolicy.validatesDomainName = false securityPolicy.allowInvalidCertificates = false

Any insight would be greatly appreciated. Thank you


回答1:


After much research and trial ... I decide to move to Alamofire 3.0 and the solution came. Note the following: The certificate must be in .der format. Mine was in .pem format. My certifcate was for the "leaf" i.e, the certificate chain was not included. For iOS 9.0 I had to add the ATS transport for my server.

Working example:

var manager: Manager

init() {
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "myserver.com": .PinCertificates(
            certificates: ServerTrustPolicy.certificatesInBundle(),
            validateCertificateChain: false,
            validateHost: true
        )
    ]

    manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
                                serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
}



let email = defaults.objectForKey("email") as? String
let beacon = defaults.objectForKey("beacon") as? String

let credential = NSURLCredential(user: email!, password: beacon!, persistence: NSURLCredentialPersistence.ForSession)

manager.request(.GET, url, encoding: .JSON)
.authenticate(usingCredential: credential)
.responseJSON { response in
    switch response.result {
    case .Success(let data):
        print(data)
        self.delegate?.didReceivePersonResults!(data as! NSDictionary)
    case .Failure(let error):
        print(error)
        self.delegate?.didReceivePersonError!("Server Error")
    }
}


来源:https://stackoverflow.com/questions/35093005/swift-afnetworking-ssl-pinning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!