-
-
Save ChandleWEi/8f8701d46610f30bf595de5ad1fd17fb to your computer and use it in GitHub Desktop.
Using NSURLSession with SSL public key pinning
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
/* | |
1. Adhere to the NSURLSessionDelegate delegate | |
2. Initialize NSURLSession and specify self as delegate (e.g. [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];) | |
3. Add the method below to your class | |
4. Change the certificate resource name | |
*/ | |
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler | |
{ | |
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; | |
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0); | |
NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate)); | |
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"myCertName" ofType:@"cer"]; | |
NSData *localCertData = [NSData dataWithContentsOfFile:cerPath]; | |
if ([remoteCertificateData isEqualToData:localCertData]) | |
{ | |
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; | |
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; | |
completionHandler(NSURLSessionAuthChallengeUseCredential, credential); | |
} | |
else | |
{ | |
[[challenge sender] cancelAuthenticationChallenge:challenge]; | |
completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment