title: Swift iOS Client Certificate Authentication
body: <p>The web service I want to consume requires a client certificate. How can I send my certificate to it?</p>
  
  <p>To further elaborate I don't understand how to create the <code>SecIdentityRef</code>.</p>
  
  <p>In my <code>NSURLConnection</code> <code>didReceiveAuthenticationChallenge</code> I've got this conditional after <code>ServerTrust</code>:</p>
  
  <pre><code>else if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate
      {
          var secIdent : SecIdentityRef = ?????????
          var certCred = NSURLCredential(identity: secIdent, certificates: [getClientCertificate()], persistence: NSURLCredentialPersistence.Permanent)
          challenge?.sender.useCredential(certCred, forAuthenticationChallenge: challenge!)
      }
  </code></pre>
  
  <p>The <code>getClientCertificate</code> method:</p>
  
  <pre><code>func getClientCertificate() -&gt; SecCertificateRef
  {
      let mainBundle : NSBundle = NSBundle.mainBundle()
      var mainBund = mainBundle.pathForResource("iosClientCert", ofType: "cer") //exported the cert in der format.
      var key : NSData = NSData(contentsOfFile: mainBund!)!
      var turnToCert : SecCertificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()
  
      return turnToCert;
  }
  </code></pre>