Skip to content

Instantly share code, notes, and snippets.

@IamSaurav
Created April 26, 2020 17:31
Show Gist options
  • Save IamSaurav/d046a8adcf63c6f605d06bfeabad5641 to your computer and use it in GitHub Desktop.
Save IamSaurav/d046a8adcf63c6f605d06bfeabad5641 to your computer and use it in GitHub Desktop.
This function is where we need to verify Server by extracting SSL certificate of server/api and validating against pinned ssl certificate.
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust else {return}
guard let serverTrustInfo = challenge.protectionSpace.serverTrust,
let certificate = serverSSLCertificate(serverTrustInfo) else {return}
// Either of the below methods "Public key pinning" or "Certificate pinning" can be done
// guard let publicKeySha256 = sha256(certificate) else {return}
// if pinnedPublicKeyHash == sha256(serverSSlPublicKey) {
// completionHandler(.useCredential, URLCredential.init(trust: serverTrustInfo))
// }else{
// completionHandler(.cancelAuthenticationChallenge, nil)
// }
if pinnedCertificateHash == sha256(certificate) {
completionHandler(.useCredential, URLCredential.init(trust: serverTrustInfo))
}else{
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment