网络及安全iOS程序猿iOS Developer

使用自签名证书配置AFNetworking(3.x)实现HTTP

2016-12-21  本文已影响229人  91阿生
1.实现HTTPS请求 --- 单项验证

针对于用AFNetworking实现https单向验证,只需要服务端提供 server.p12
双击安装
打开钥匙
找到你刚安装的证书,导出此证书,选择文件格式为 .cer , 命名随你(建议使用英文)


19BF395E-69C5-4455-AF6D-D65149D3EF27.png

把生成的 server.cer 拖入你的项目中
代码(代码未封装):
- (void)post:(NSString *)url withParameters:(id)parameters success:(void (^)(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject))success failure:(void (^)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error))failure {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
securityPolicy.allowInvalidCertificates = YES; //是否允许使用自签名证书
securityPolicy.validatesDomainName = NO; //是否需要验证域名

      self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
      self.manager.responseSerializer = [AFJSONResponseSerializer serializer];
      self.manager.securityPolicy = securityPolicy;

      self.manager.responseSerializer.acceptableContentTypes  = [NSSet setWithObjects:@"application/xml",@"text/html",@"text/xml",@"text/plain",@"application/json",nil];

      __weak typeof(self) weakSelf = self;
      [self.manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {
             /// 获取服务器的trust object
             SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
            /// 导入自签名证书
            #warning 注意将你的证书加入项目,并把下面名称改为自己证书的名称
            NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"xxx.cer" ofType:@"cer"];
            NSData* caCert = [NSData dataWithContentsOfFile:cerPath];
            if (!caCert) {
                 NSLog(@" ===== .cer file is nil =====");
                return 0;
             }
            NSArray *cerArray = @[caCert];
            weakSelf.manager.securityPolicy.pinnedCertificates = [NSSet setWithArray:cerArray];
    
            SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);
            NSCAssert(caRef != nil, @"caRef is nil");
    
            NSArray *caArray = @[(__bridge id)(caRef)];
            NSCAssert(caArray != nil, @"caArray is nil");
    
             /// 将读取到的证书设置为serverTrust的根证书
            OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);
            SecTrustSetAnchorCertificatesOnly(serverTrust,NO);
            NSCAssert(errSecSuccess == status, @"SecTrustSetAnchorCertificates failed");
    
            /// 选择质询认证的处理方式
            NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
           __autoreleasing NSURLCredential *credential = nil;
    
           /// NSURLAuthenticationMethodServerTrust质询认证方式
           if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
                /// 基于客户端的安全策略来决定是否信任该服务器,不信任则不响应质询。
                if ([weakSelf.manager.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 {
        disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    }
    
    return disposition;
}];

[self.manager POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
     NSLog(@"%@", responseObject);
  ) {
        success(task,responseObject);
    }

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 
      if (failure) {
          failure(task,error);
      }
  }];
}

以上就是单项验证的步骤和代码.

2.实现HTTPS请求 --- 双向验证

针对于用AFNetworking实现https单向验证,只需要服务端提供 server.p12 和 客服端所使用的client.p12
只需要安装server.p12, 导出server.cer(同单向验证)
拖入导出的server.cer 和 client.p12 到项目中

具体可以看下github上的demo: https://github.com/StephentTom/-AFNetworking-3.x-HTTPS-.git

上一篇下一篇

猜你喜欢

热点阅读