美文网首页
AFN实现SSL双向验证

AFN实现SSL双向验证

作者: A_Yun | 来源:发表于2023-08-14 10:09 被阅读0次
    /// Post 请求
    - (void)initNetwork_Configuration {
        
        NSString *urlPath = @"";
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        
        //创建manager时没有设定BaseURL则会报错。
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:urlPath]];
        AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", @"application/javascript", nil];
        //AFNetworking默认把响应结果当成JSON来处理
        manager.responseSerializer = responseSerializer;
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //开启https ssl验证
        if (OpenHTTPSURLVerify) {
            [manager setSecurityPolicy:[self customSecurityPolicy]];
            [self checkCredential:manager];
        } else{
            //https不验证证书添加
            manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
            manager.securityPolicy.allowInvalidCertificates = YES;
            [manager.securityPolicy setValidatesDomainName:NO];
        }
        
        
        
        [manager POST:urlPath parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          
            NSString *data = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Success信息:%@",data);
            
            //如果需要知道这个HTTP的所有信息,就需要获得NSURLResponse的子类
            //拿到响应头信息
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
             
            if ((httpResponse.statusCode / 100) != 2) {
               //提示错误信息
    
            } else {
                //请求成功回调
    
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           
            NSLog(@"NSError信息:%@",error);
            if (error != nil) {
               //提示错误信息
    
            }
        }];
            
    }
    

    加载服务端证书

    - (AFSecurityPolicy*)customSecurityPolicy {
        
        //开启证书校验
        AFSSLPinningMode pinMode = AFSSLPinningModeCertificate;
        
        //使用证书验证模式
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:pinMode];
        //allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
        securityPolicy.allowInvalidCertificates = YES;
        
        //validatesDomainName 是否需要验证域名,默认为YES;
        //假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
        //置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
        //如置为NO,建议自己添加对应域名的校验逻辑。https://www.scycyt.com/ssl/ssl/hello
        securityPolicy.validatesDomainName = NO;
        
        //导入证书(der、cer、crt都可以)
        //NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"" ofType:@"der"];
        // NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"" ofType:@"cer"];
        NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"" ofType:@"crt"];
        NSData *certData = [NSData dataWithContentsOfFile:cerPath];
        NSSet *set = [NSSet setWithObjects:certData, nil];
        securityPolicy.pinnedCertificates = set;
        
        return securityPolicy;
    }
    

    校验证书

    //校验证书
    - (void)checkCredential:(AFURLSessionManager *)manager
    {
        [manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
            NSLog(@"校验证书错误:%@", error);
        }];
        __weak typeof(manager)weakManager = manager;
        [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
            NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            __autoreleasing NSURLCredential *credential =nil;
            NSLog(@"authenticationMethod=%@",challenge.protectionSpace.authenticationMethod);
            //判断服务器要求客户端的接收认证挑战方式,如果是NSURLAuthenticationMethodServerTrust则表示去检验服务端证书是否合法,NSURLAuthenticationMethodClientCertificate则表示需要将客户端证书发送到服务端进行检验
            if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
                // 基于客户端的安全策略来决定是否信任该服务器,不信任的话,也就没必要响应挑战
                if([weakManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                    // 创建挑战证书(注:挑战方式为UseCredential和PerformDefaultHandling都需要新建挑战证书)
                    credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                    // 确定挑战的方式
                    if (credential) {
                        //证书挑战  设计policy,none,则跑到这里
                        disposition = NSURLSessionAuthChallengeUseCredential;
                    } else {
                        disposition = NSURLSessionAuthChallengePerformDefaultHandling;
                    }
                } else {
                    disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
                }
            } else { //只有双向认证才会走这里
                // client authentication
                SecIdentityRef identity = NULL;
                SecTrustRef trust = NULL;
    //p12、pfx都可以
    //            NSString *p12 = [[NSBundle mainBundle] pathForResource:@"new" ofType:@"pfx"];
                NSString *p12 = [[NSBundle mainBundle] pathForResource:@"Client-Test-Cert-User3" ofType:@"pfx"];
                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;
                    }
                }
            }
            *_credential = credential;
            return disposition;
        }];
    }
    
    //读取p12文件中的密码
    - (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
        OSStatus securityError = errSecSuccess;
        //client certificate password
        NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"user3"
                                                                     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;
    }
    

    相关文章

      网友评论

          本文标题:AFN实现SSL双向验证

          本文链接:https://www.haomeiwen.com/subject/zjzqmdtx.html