寫在前面:
1.相關(guān)https具體內(nèi)容本篇就不再描述。
2.前幾天公司項(xiàng)目要求配置https雙向認(rèn)證,由于是銀行業(yè)務(wù)耕陷,證書是cfca(中國金融認(rèn)證中心)頒發(fā)的掂名,因此 在這里我就不描述自簽名證書的具體。iOS自簽名證書哟沫,我沒有調(diào)試饺蔑,據(jù)說是不認(rèn)自簽名的。自簽名證書中嗜诀,這里有篇博客講的非常好猾警,這篇幫我在本地搭建了雙向認(rèn)證的tomcat服務(wù)器。http://blog.csdn.net/jerryvon/article/details/8548802
3.這篇博客側(cè)重于 iOS客戶端相關(guān)內(nèi)容的描述隆敢,OC語言发皿,基于AFNetwork3.0版本。
本篇內(nèi)容
1.https雙向認(rèn)證中拂蝎,iOS客戶端需要哪兩個(gè)證書穴墅,什么格式的。
2.ATS設(shè)置
3.普通https請(qǐng)求證書驗(yàn)證代碼 ?與 ?uiwebview請(qǐng)求https頁面時(shí)驗(yàn)證代碼
4.html中ajax請(qǐng)求https
1.服務(wù)器公鑰和p12文件温自。服務(wù)器公鑰網(wǎng)上很多代碼是.cer格式的玄货,但是在AF3.0版本中,支持的是.der格式悼泌,這個(gè)坑請(qǐng)注意了松捉。
對(duì)公鑰證書data的描述
這個(gè)方法添加的是公鑰證書的data數(shù)據(jù)
p12證書 對(duì)應(yīng)的是服務(wù)器上的 .pfx證書(應(yīng)該是,不太確定)馆里,pfx格式的可以轉(zhuǎn)換成p12證書隘世,它里面包括了公鑰和私鑰,客戶端用p12證書應(yīng)該是在做客戶端的驗(yàn)證鸠踪。
這是我自己配置的tomcat配置以舒,p12證書對(duì)應(yīng)的是 keystoreFile所對(duì)應(yīng)的證書。
注意:在添加讀取證書的時(shí)候慢哈,Xcode7有個(gè)bug 但不是必現(xiàn)蔓钟。當(dāng)證書拖到項(xiàng)目中時(shí),路徑讀不出來卵贱,找不到這個(gè)文件滥沫,但是Bundle Resource中卻偏偏存在,當(dāng)時(shí)我一直認(rèn)為是證書的問題键俱,糾結(jié)了很久兰绣。
這里添加證書,一般可以解決無法讀取路徑的問題
這個(gè)證書路徑容易讀出來是 nil
2.ATS設(shè)置
這個(gè)也是我一個(gè)不是特別能想的通的問題编振,按道理說缀辩,這個(gè)是設(shè)置在iOS9之后請(qǐng)求http才會(huì)設(shè)置的,但是在請(qǐng)求https的時(shí)候我發(fā)現(xiàn) 不設(shè)置的話,證書并沒有進(jìn)行驗(yàn)證臀玄。
因此還是要設(shè)置一下瓢阴。
這里的域名下,TLS傳輸協(xié)議需要服務(wù)器端的注意一下健无,iOS支持的是1.2版本開始荣恐。但是很多都是從1.0開始的。因此我們最好也配上去累贤。
3.請(qǐng)求https服務(wù)源代碼
與正常的AFN請(qǐng)求http請(qǐng)求來說叠穆,添加一這一個(gè)設(shè)置
```
-(AFSecurityPolicy*) getCustomHttpsPolicy:(AFHTTPSessionManager*)manager{
//https 公鑰證書配置
NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"custom" ofType:@"der"];
NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
NSSet *certSet = [NSSet setWithObject:certData];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];
policy.allowInvalidCertificates = YES;
policy.validatesDomainName = NO;//是否校驗(yàn)證書上域名與請(qǐng)求域名一致
//https回調(diào) 客戶端驗(yàn)證
[manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
NSLog(@"setSessionDidBecomeInvalidBlock");
}];
__weak typeof(manager)weakManger = manager;
__weak typeof(self)weakSelf = self;
//客戶端請(qǐng)求驗(yàn)證 重寫 setSessionDidReceiveAuthenticationChallengeBlock 方法
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing NSURLCredential *credential =nil;
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if([weakManger.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 {
// client authentication
SecIdentityRef identity = NULL;
SecTrustRef trust = NULL;
NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client"ofType:@"p12"];
NSFileManager *fileManager =[NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:p12])
{
NSLog(@"client.p12:not exist");
}
else
{
NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
if ([[weakSelf class]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;
}];
return policy;
}
```
```
+ (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError = errSecSuccess;
//client certificate password
NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"111111"
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;
}
```
UIWebview加載雙向認(rèn)證https頁面
這里需要注意一下,這個(gè)需要設(shè)置
設(shè)置臼膏,請(qǐng)求忽略本地緩存在性能上會(huì)有所犧牲硼被。在https請(qǐng)求中,據(jù)說90%多cpu消耗都是花費(fèi)在證書的校驗(yàn)過程當(dāng)中渗磅。但是祷嘶,當(dāng)html頁面中使用的ajax請(qǐng)求方式也是https的時(shí)候,這個(gè)就必須重新驗(yàn)證夺溢。原因是,當(dāng)uiwebview驗(yàn)證完證書烛谊,之后风响,再次啟動(dòng)app,webview會(huì)根據(jù)connection返回的驗(yàn)證歷史信息丹禀,直接認(rèn)為客戶端是安全的状勤,不再進(jìn)行證書校驗(yàn),這個(gè)時(shí)候双泪,html頁面里面的ajax請(qǐng)求就不能正常的發(fā)送持搜,會(huì)導(dǎo)致無法正常運(yùn)行。
主要代碼:
```
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *tmp = [request.URL absoluteString];
NSLog(@"request url :%@",tmp);
if ([request.URL.scheme rangeOfString:@"https"].location != NSNotFound) {
//開啟同步的請(qǐng)求去雙向認(rèn)證
if (!_Authenticated) {
originRequest = request;
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
[webView stopLoading];
return false;
}
}
return YES;
}
```
```
#pragma NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSURLCredential * credential;
assert(challenge != nil);
credential = nil;
NSLog(@"----received challenge----");
NSString *authenticationMethod = [[challenge protectionSpace] authenticationMethod];
if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"----server verify client----");
NSString *host = challenge.protectionSpace.host;
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
BOOL validDomain = false;
NSMutableArray *polices = [NSMutableArray array];
if (validDomain) {
[polices addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)host)];
}else{
[polices addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)polices);
//pin mode for certificate
NSString *path = [[NSBundle mainBundle] pathForResource:@"custom" ofType:@"der"];
NSData *certData = [NSData dataWithContentsOfFile:path];
NSMutableArray *pinnedCerts = [NSMutableArray arrayWithObjects:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData), nil];
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCerts);
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
} else {
NSLog(@"----client verify server----");
SecIdentityRef identity = NULL;
SecTrustRef trust = NULL;
NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:p12]) {
NSLog(@"client.p12 file not exist!");
}else{
NSData *pkcs12Data = [NSData dataWithContentsOfFile:p12];
if ([[self class] 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];
}
}
}
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
}
```
```
+ (BOOL)extractIdentity:(SecIdentityRef *)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityErr = errSecSuccess;
//client certificate password
NSDictionary *optionsDic = [NSDictionary dictionaryWithObject:@"111111" forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityErr = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data, (__bridge CFDictionaryRef)optionsDic, &items);
if (securityErr == errSecSuccess) {
CFDictionaryRef mineIdentAndTrust = CFArrayGetValueAtIndex(items, 0);
const void *tmpIdentity = NULL;
tmpIdentity = CFDictionaryGetValue(mineIdentAndTrust, kSecImportItemIdentity);
*outIdentity = (SecIdentityRef)tmpIdentity;
const void *tmpTrust = NULL;
tmpTrust = CFDictionaryGetValue(mineIdentAndTrust, kSecImportItemTrust);
*outTrust = (SecTrustRef)tmpTrust;
}else{
return false;
}
return true;
}
```
```
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse {
_Authenticated = YES;
//webview 重新加載請(qǐng)求焙矛。
[localWebView loadRequest:originRequest];
[connection cancel];
}
```
還值得注意的是:在https方式加載html的時(shí)候葫盼,我查到大量的資料中,都是在
```
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
```
這三個(gè)方法去處理的村斟,方式是:將收到的data拼成一個(gè)全局的變量贫导,在連接完成時(shí)將data轉(zhuǎn)換成字符串,用加載本地html的方式進(jìn)行加載蟆盹。
這個(gè)方法不可行孩灯,在加載非本地html的時(shí)候。
js逾滥、css峰档、圖片的引入都是根據(jù)相對(duì)路徑的
在html前端頁面中,會(huì)有大量的外部資源引用。當(dāng)將html頁面元素當(dāng)做字符串去加載的時(shí)候讥巡,就會(huì)存在html依賴的外部資源無法加載掀亩,html頁面會(huì)出現(xiàn)圖片找不到或者布局混亂的現(xiàn)象。當(dāng)使用loadHTMLString中的baseURL作為相對(duì)路徑的指導(dǎo)時(shí)尚卫,在加載本地資源時(shí)归榕,使用的是bundle,但是加載遠(yuǎn)程資源時(shí)吱涉,就會(huì)觸發(fā)https證書驗(yàn)證的方法刹泄,無限次的循環(huán),整個(gè)app高消耗內(nèi)存和cpu怎爵,關(guān)鍵是還加載不到特石。
因此,在收到pResponse的時(shí)候鳖链,直接斷掉connection姆蘸,重新加載該頁面就ok。這個(gè)時(shí)候芙委,客戶端和服務(wù)器都是相互信任的逞敷,ssl通道已經(jīng)建立起來,大家可以愉快的進(jìn)行操作了灌侣。
ajax https請(qǐng)求
這個(gè)其實(shí)是個(gè)偽問題推捐,在https方法加載的頁面當(dāng)中,已經(jīng)建立起來ssl通道的web環(huán)境侧啼,直接就可以進(jìn)行https請(qǐng)求牛柒。因此是不需要進(jìn)行像客戶端那樣配置。
但是痊乾,如果是http方式加載的頁面中皮壁,進(jìn)行https請(qǐng)求,那么久存在跨域的問題哪审。這個(gè)在下篇中再進(jìn)行解釋蛾魄。
因此,在html頁面是以https方法加載的情況下湿滓,不用考慮證書的問題畏腕,直接把請(qǐng)求方式改成https,完事茉稠。
來源: http://www.reibang.com/p/13f6d134a59a