iOS实用教程之Https双向认证详解

前言

年前的时候,关于苹果要强制https的传言四起,虽然结果只是一个“谣言”,但是很明显的这是迟早会到来的,间接上加速了各公司加紧上https的节奏,对于iOS客户端来说,上https需不需要改变一些东西取决于---------对,就是公司有没有钱。土豪公司直接买买买,iOS开发者只需要把http改成https完事。然而很不幸,我们在没钱的公司,选择了自签证书。虽然网上很多关于https的适配,然而很多都是已过时的,这里我们主要是讲一下https双向认证。

【证书选择】自签

【网络请求】原生NSURLSession或者AFNetworking3.0以上版本

【认证方式】双向认证

Https双向认证过程

先来了解一下双向认证的大体过程:(图片来自网络,如果是某位博主原创的请私信我)


下面我们一步步来实现

1、设置服务端证书

NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];

NSData *certData = [NSData dataWithContentsOfFile:certFilePath];

NSSet *certSet = [NSSet setWithObject:certData];

AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];

policy.allowInvalidCertificates = YES;

policy.validatesDomainName = NO;

self.afnetworkingManager.securityPolicy = policy;

2、处理挑战

原生的NSURLSession是在

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler

代理方法里面处理挑战的,再看看AFNetworking在该代理方法里处理的代码

if (self.taskDidReceiveAuthenticationChallenge) {

disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);

} else {

...

}

我们只需要给它传递一个处理的block

[self.afnetworkingManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {

...

}

根据传来的challenge生成disposition(应对挑战的方式)和credential(客户端生成的挑战证书)

3、服务端认证

当challenge的认证方法为NSURLAuthenticationMethodServerTrust时,需要客户端认证服务端证书

//评估服务端安全性

if([weakSelf.afnetworkingManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {

//创建凭据

credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

if(credential) {

disposition =NSURLSessionAuthChallengeUseCredential;

} else {

disposition =NSURLSessionAuthChallengePerformDefaultHandling;

}

} else {

disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;

}

4、客户端认证

认证完服务端后,需要认证客户端

由于是双向认证,这一步是必不可省的

SecIdentityRef identity = NULL;

SecTrustRef trust = NULL;

NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client"ofType:@"p12"];

NSFileManager *fileManager =[NSFileManager defaultManager];

if(![fileManager fileExistsAtPath:p12])

{

NSLog(@"client.p12:not exist");

}

else

{

NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];

if ([[weakSelf class]extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])

{

SecCertificateRef certificate = NULL;

SecIdentityCopyCertificate(identity, &certificate);

const void*certs[] = {certificate};

CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);

credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];

disposition =NSURLSessionAuthChallengeUseCredential;

}

}

+ (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {

OSStatus securityError = errSecSuccess;

//client certificate password

NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"your p12 file pwd"

forKey:(__bridge id)kSecImportExportPassphrase];

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);

if(securityError == 0) {

CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);

const void*tempIdentity =NULL;

tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);

*outIdentity = (SecIdentityRef)tempIdentity;

const void*tempTrust =NULL;

tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);

*outTrust = (SecTrustRef)tempTrust;

} else {

NSLog(@"Failedwith error code %d",(int)securityError);

return NO;

}

return YES;

}

原生NSURLSession双向认证

在原生的代理方法里面认证就行,代码基本和AFNetworking的一致,注意最后需要调用

completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

来执行回调操作

关于UIWebView的Https双向认证

网上的资料大体上有几种解决方法

1:跳过Https认证(这还能跳过?没试过,不太靠谱)

2:中断原有的请求步骤,将request拿出来,下载完整的HTML代码,让webView加载该代码(在单页面展示的情况下基本满足使用,但是在部分标签不是独立跳转https路径的时候,将出现无法加载的情况,不是很好用)

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

NSString * urlString = [request.URL absoluteString];

if ([urlString containsString:URL_API_BASE]) {

[[SUHTTPOperationManager manager]REQUEST:request progress:nil handler:^(BOOL isSucc, id responseObject, NSError *error) {

NSString * htmlString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

BASE_INFO_FUN(@"下载HTML完毕");

[self loadHTMLString:htmlString baseURL:nil];

}];

return NO;

}

return YES;

}

3、中断原有的请求步骤,将request拿出来,完成鉴权认证之后,再让webView重新请求该request(这种方式理论上好像可以,我试过,没有成功,可能我打开的方式不正确)

4、或许,您有更好的解决方案 - -

关于代码

网上很多https双向认证的代码,基本是一样的,这里我们直接拿来用就可以,前提是我们不能单纯copy,而是在理解其实现的基础上,整合到工程中,遇到问题解决思路清晰,而不是一脸懵逼。

总结

以上是 iOS实用教程之Https双向认证详解 的全部内容, 来源链接: utcz.com/z/319722.html

回到顶部