The web service I want to consume requires a client certificate. How can I send my certificate to it?
To further elaborate I don\'t understand how to create the
I am using last xcode and swift version, and this code work for me, using a client certificate .pfx, based on Bins Ich answer:
func extractIdentity(certData:NSData) -> IdentityAndTrust {
var identityAndTrust:IdentityAndTrust!
var securityError:OSStatus = errSecSuccess
var items:Unmanaged?
let certOptions:CFDictionary = [ kSecImportExportPassphrase.takeRetainedValue() as String: "password" ];
// import certificate to read its entries
securityError = SecPKCS12Import(certData, certOptions, &items);
if securityError == errSecSuccess {
let certItems:CFArray = items?.takeUnretainedValue() as CFArray!;
let certItemsArray:Array = certItems as Array
let dict:AnyObject? = certItemsArray.first;
if let certEntry:Dictionary = dict as? Dictionary {
// grab the identity
let identityPointer:AnyObject? = certEntry["identity"];
let secIdentityRef:SecIdentityRef = identityPointer as! SecIdentityRef!;
// grab the trust
let trustPointer:AnyObject? = certEntry["trust"];
let trustRef:SecTrustRef = trustPointer as! SecTrustRef;
// grab the cert
let chainPointer:AnyObject? = certEntry["chain"];
let chainRef:SecCertificateRef = chainPointer as! SecCertificateRef;
let certArray:CFArrayRef = chainRef as! CFArrayRef
identityAndTrust = IdentityAndTrust(identityRef: secIdentityRef, trust: trustRef, certArray: certArray);
}
}
return identityAndTrust;
}
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
let strTemp = challenge.protectionSpace.authenticationMethod
if(strTemp == NSURLAuthenticationMethodServerTrust) {
challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}
if(strTemp == NSURLAuthenticationMethodClientCertificate) {
let certFile = NSBundle.mainBundle().pathForResource("mycert", ofType:"pfx")
let p12Data = NSData(contentsOfFile:certFile!)
let identityAndTrust:IdentityAndTrust = extractIdentity(p12Data!)
let urlCredential:NSURLCredential = NSURLCredential(
identity: identityAndTrust.identityRef,
certificates:identityAndTrust.certArray as [AnyObject],
persistence: NSURLCredentialPersistence.Permanent)
challenge.sender.useCredential(urlCredential ,forAuthenticationChallenge:challenge)
}
}