【发布时间】:2020-11-13 17:22:05
【问题描述】:
我正在尝试使用自签名证书将 SSL 固定添加到我的应用程序,但我似乎无法让它工作。 我已经尝试了所有在互联网上可以找到的东西,但都没有成功,而且不是 SSL 工作原理方面的专家也无济于事。
我正在将 Objective-c 与最新版本的 AFNetworking 一起使用。
我编写了一段非常简单的代码来测试我的 API 调用(我在这篇文章中使用了占位符 URL):
NSString *url = @"https://api.example.net/webservice";
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"example.net" ofType:@"der"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
manager.requestSerializer = [AFJSONRequestSerializer new];
manager.responseSerializer = [AFJSONResponseSerializer new];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setAllowInvalidCertificates:YES];
[policy setValidatesDomainName:NO];
policy.pinnedCertificates = [NSSet setWithObject:certData];
manager.securityPolicy = policy;
[manager POST:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"SUCCESS");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"FAILURE : %@", error.localizedDescription);
}];
每次我尝试执行此代码时,都会失败并出现以下错误:
Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “api.example.net” which could put your confidential information at risk."
我尝试为我的证书使用不同的格式(.der、.cer、...),但我仍然总是遇到同样的错误。
我尝试在 info.plist 中使用 NSAllowsArbitraryLoads,但没有任何变化。
为了确保我使用的是工作代码,我还从Ray Wenderlich tutorial 下载了示例项目,但我自己的证书仍然无效(在教程中他们使用 stackexchange 证书,这个有效)。
我研究这个问题好几天了,还没有找到解决办法。
相同的证书在我们的 Android 应用以及 Postman 上完美运行。
这是因为我使用自签名证书而 iOS 不喜欢它吗? 我的代码或应用程序配置中是否有任何明显的遗漏? 是否有特定的东西来实现服务器端以确保它与 iOS 一起工作? 我必须以非常特定的格式导出我的证书吗?
欢迎提供任何信息。
谢谢!
【问题讨论】:
标签: ios objective-c ssl afnetworking pinning