Search code examples
iosswifthttpsswift2alamofire

Using a client certificate with Alamofire 2.0


On Alamofire 1 and Swift 1.2 I used the following code to issue a request, submitting my own client certificate:

Alamofire.request(.POST, url!, parameters: params, encoding: .JSON)
    .authenticate(usingCredential: credential)
    .responseJSON { (request, response, JSON, error) in
        ...
    }

With Alamofire and Swift 2.0 I adopted pinned certificates and use my own Manager instance. However the server reports that no valid certificate was submitted.

let manager = Manager(
    configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
    serverTrustPolicyManager: ServerTrustPolicyManager(policies:
        ["my.server.com": ServerTrustPolicy.PinCertificates(certificates: [
            SecCertificateCreateWithData(kCFAllocatorDefault,
                NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("root-ca", ofType: "der")!)!)!
            ],
            validateCertificateChain: true, validateHost: true)
        ])
    )

What am I doing wrong? I don't have access to the server to see what the incoming requests looks like. However, the following cURL requests is accepted:

curl -X POST -d '{"foo": "bar"}' https://my.server.com --cert client.pem --insecure

Thank you for your help!


Solution

  • Well, the code above works! I tried to isolate the problem by creating a blank project and to add one piece at a time until I found the bug. Since I could not reproduce it I decided to get rid of all CocoaPods directories in my actual project and to rebuild the whole workspace. Turns out this solved the problem. Rebuilding the workspace without getting rid of the existing directories apparently wasn't enough.