AFNetworking 3.0实现https双向认证

释放双眼,带上耳机,听听看~!

目的

为了能使用安全的http通道,避免路由劫持,抓包等方法窃取重要数据,为了实现苹果ATS(App Transport Security),使用https(http通道加入SSL层)通道加密进行接口设计,达到网络数据安全的目的。项目需求,加上苹果无限期延迟ATS的要求,在未来,https必须会使用。

证书

在https双向认证的要求下,服务端需要签发服务器证书和客户端证书。iOS所需要的证书如下:

  • 服务端.cer(server.cer)
  • 客户端.p12(client.p12)

使用AFNetworking 3.0

AFHTTPSessionManager

 

+ (AFHTTPSessionManager *)networkingManager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];   
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    //启动证书验证
    manager.securityPolicy = [self securityPolicy];
    [manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
        LPLog(@"%@",error.localizedDescription);
    }];
   //启用双向认证需要下面的代码,如果只是单向认证则不需要下面代码,下面是开启客户端验证的代码。
    __weak typeof(manager)weakSelf = manager;
    [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
        __strong typeof(manager) man = weakSelf;
        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        __autoreleasing NSURLCredential *credential =nil;
        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            if([man.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;
            }
        } else {
            // 客户端验证
            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 ([self 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;
                    CFRelease(certArray);
                }
            }
        }
        *_credential = credential;
        return disposition;
    }];
    return manager;
}

启用服务器证书验证

 

+ (AFSecurityPolicy *)securityPolicy
{
    //服务器证书的路径,开启服务器验证
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    //允许自建证书
    securityPolicy.allowInvalidCertificates = YES;   
    //关闭域名验证
    securityPolicy.validatesDomainName = NO;   
    securityPolicy.pinnedCertificates = [NSSet setWithObjects:certData, nil];
    return securityPolicy;
}

验证客户端证书

 

+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
    OSStatus securityError = errSecSuccess;
    //客户端证书密码
    NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"123456"
                                                                 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 {
        return NO;
    }
    return YES;
}

问题

客户端证书和服务器证书都必须由服务器生成,如果验证失败,很大可能就是证书生成错误的问题。

 

人已赞赏
iOS文章

OC与Swift混编,互相导入三方库

2019-12-22 15:36:52

iOS文章

iOS NSUserDefaults存储自定义模型数据

2019-12-22 17:44:00

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索