Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SSL Pinning PK Example
override func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// 1
guard
challenge.protectionSpace.host == baseURL.host,
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust
else {
completionHandler(.performDefaultHandling, nil)
return
}
// 2
var error: CFError?
let success = SecTrustEvaluateWithError(trust, &error)
guard
success,
let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0)
else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// 3
let serverCertificateCFData = SecCertificateCopyData(serverCertificate)
guard
let serverCertData = CFDataGetBytePtr(serverCertificateCFData),
let filePath = Bundle.main.path(forResource: "production-api", ofType: "cer")
else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let fileURL = URL(fileURLWithPath: filePath)
let serverCert = Data(bytes: serverCertData, count: CFDataGetLength(serverCertificateCFData))
// 4
guard
let fileCert = try? Data(contentsOf: fileURL),
serverCert == fileCert
else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
completionHandler(.performDefaultHandling, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment