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

2020-01-20 23:07:25王冬梅

前言

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

【证书选择】自签

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

【认证方式】双向认证

Https双向认证过程

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

https,双向认证,ios

下面我们一步步来实现

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;
   }