使用AFNetworking验证自签名证书

4
我想将我的iOS应用程序与AFNetwork连接到使用自签名证书的web服务器。我在github上找到了一个解决方案(https://github.com/AFNetworking/AFNetworking/pull/694)。我尝试了一下,证书固定似乎可以工作,但是我遇到了另一个错误:
错误域=NSURLErrorDomain Code=-1012 "操作无法完成。(NSURLErrorDomain error -1012.)" UserInfo=0x7bc2090 {NSErrorFailingURLKey=(我的域)}
有人知道这个错误是否与AFNetworking框架和自签名证书有关吗?
已解决: 我找到了解决错误的方法。我必须将SSLPinningMode设置为AFSSLPinningModeCertificate,现在它可以工作了。
AFJSONRequestOperation *operation =[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSDictionary *resDictionary = (NSDictionary *)JSON;
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"%@",error);
}];
operation.SSLPinningMode = AFSSLPinningModeCertificate;
[operation start];

你能展示一下代码吗?这个错误是通用的,可能由许多原因引起。 - Raptor
我没有使用任何特殊代码,只是使用标准的JSON响应'AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)' 当我将'AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES'定义为1时,它可以正常工作。 - Weini
为您添加了问题中的代码。 - Raptor
1个回答

0

试试这个解决方法。

AFJSONRequestOperation *operation =[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSDictionary *resDictionary = (NSDictionary *)JSON;
}
                                                                                   failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                                                       NSLog(@"%@",error);
                                                                                   }];
operation.securityPolicy.allowInvalidCertificates = YES;
[operation start];

2
允许无效证书是一个可怕的想法!它会解决这个错误,但也会使应用程序变得完全不安全。 - bdesham
我同意使用安全层,但如果某些Web服务使用SSL证书,则无法测试没有SSL证书的Web服务。如果没有其他解决方案来测试没有SSL证书的HTTPS Web服务,为什么要给出-1? - Voda Ion
正如问题的更新所述,通过设置 operation.SSLPinningMode 可以解决该问题。这完全解决了 OP 遇到的问题,因此没有必要采取像设置 allowInvalidCertificates 这样的激进解决方案。 - bdesham
1
换句话说,您的解决方案在某些调试情况下可能有所帮助,但它不是对于这个问题的一个好答案。 - bdesham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接