Created
March 25, 2020 07:38
-
-
Save Jimmy-Prime/fdf018be8a3c0c46ec80d6896b671865 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class SessionDelegate: NSObject, URLSessionDelegate { | |
func urlSession( | |
_ session: URLSession, | |
didReceive challenge: URLAuthenticationChallenge, | |
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void | |
) { | |
guard challenge.protectionSpace.host != URL.sns.host else { | |
completionHandler(.performDefaultHandling, nil) | |
return | |
} | |
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, | |
let serverTrust = challenge.protectionSpace.serverTrust, | |
let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else { | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
return | |
} | |
let remoteData = SecCertificateCopyData(serverCertificate) | |
let remoteCert = NSData(bytes: CFDataGetBytePtr(remoteData), length: CFDataGetLength(remoteData)) as Data | |
let candidates = [URL.mib.host!] | |
if tryCertificates(with: candidates, remoteCert: remoteCert) { | |
completionHandler(.useCredential, .init(trust: serverTrust)) | |
} else { | |
completionHandler(.cancelAuthenticationChallenge, nil) | |
} | |
} | |
private func tryCertificates(with names: [String], remoteCert: Data) -> Bool { | |
guard let name = names.first, | |
let url = Bundle.main.url(forResource: name, withExtension: "der"), | |
let localCert = try? Data(contentsOf: url) else { | |
return false | |
} | |
if remoteCert == localCert { | |
return true | |
} else { | |
return tryCertificates(with: Array(names.dropFirst()), remoteCert: remoteCert) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment