最近,我刚刚把http 转化为https,给还在纠结中的朋友们指导一二。
1、准备证书
首先找后台要一个证书(SSL证书,一般你跟后台说要弄https,然后让他给你个证书,他就知道了),我们需要的是.cer的证书。但是后台可能给我们的是.crt的证书。我们需要转换一下:打开终端 -> cd到.crt证书路径 -> 输入openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der,证书就准备好了,拖入工程,记得选copy。
文件截图2、修改AFN中问题,我看网上有新建一个类或类方法的
我是在AFHTTPSessionManager这个类中- (instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration 方法中直接添加的
__weak typeof(self) weakSelf = self;
[self setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {
/// 获取服务器的trust object
SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];
// 导入自签名证书
//#warning 注意将你的证书加入项目,并把下面名称改为自己证书的名称
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"证书名字" ofType:@"cer"];
NSData* caCert = [NSData dataWithContentsOfFile:cerPath];
if (!caCert) {
NSLog(@" ===== .cer file is nil =====");
return nil;
}
NSSet *cerArray =[NSSet setWithObject:caCert];
weakSelf.securityPolicy.pinnedCertificates = 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.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;
}];
如果你的项目中不含有webView wkWebView ,将这个设置为NO或者删掉,但是如果含有哪两种的话,建议参考这个http://www.wosign.com/faq/faq-ios10-ats.htm
如果有不对的地方请多指教。。。。。
网友评论