iOS之Https自簽名證書(shū)認(rèn)證及數(shù)據(jù)請(qǐng)求的封裝原理
摘要: 在WWDC 2016開(kāi)發(fā)者大會(huì)上,蘋(píng)果宣布了一個(gè)最后期限:到2017年1月1日 App Store中的所有應(yīng)用都必須啟用 App Transport Security安全功能。App Transport Security(ATS)是蘋(píng)果在iOS 9中引入的一項(xiàng)隱私保護(hù)功能,屏蔽明文HTTP資源加載,連接必須經(jīng)過(guò)更安全的HTTPS。蘋(píng)果目前允許開(kāi)發(fā)者暫時(shí)關(guān)閉ATS,可以繼續(xù)使用HTTP連接,但到年底所有官方商店的應(yīng)用都必須強(qiáng)制性使用ATS。
項(xiàng)目中使用的框架是AFNetworking 3.0及以上版本,由于ATS的原因,iOS只允許使用Https開(kāi)頭的鏈接,在2016年12月30日以前蘋(píng)果允許繞開(kāi)ATS,如下圖所示:
但是從2017年1月1日開(kāi)始將不再接受使用http加載資源的應(yīng)用,因此本篇文章主要講解如何使用AFN進(jìn)行自簽名證書(shū)的通過(guò)認(rèn)證(注:對(duì)于使用CA機(jī)構(gòu)認(rèn)證的證書(shū)不需要進(jìn)行認(rèn)證,直接使用Https開(kāi)頭的鏈接進(jìn)行數(shù)據(jù)訪問(wèn)和加載頁(yè)面即可)項(xiàng)目已經(jīng)上傳至GitHub(需要參考源碼的話(huà)請(qǐng)點(diǎn)擊鏈接):HttpsSignatureCertificate_jb51.rar
1,建立一個(gè)根類(lèi) 此處命名為AKNetPackegeAFN
1> .h文件 ,創(chuàng)建所需要的Get 與 Post 方法
#import <Foundation/Foundation.h> typedef enum{ AKNetWorkGET , /**< GET請(qǐng)求 */ AKNetWorkPOST = 1 /**< POST請(qǐng)求 */ }AKNetWorkType; typedef void (^HttpSuccess)(id json); typedef void (^HttpErro)(NSError* error); @interface AKNetPackegeAFN : NSObject +(instancetype)shareHttpManager; /* * netWorkType:請(qǐng)求方式 GET 或 POST signature:是否使用簽名證書(shū),是的話(huà)直接寫(xiě)入證書(shū)名字,否的話(huà)填nil api:請(qǐng)求的URL接口 parameters:請(qǐng)求參數(shù) sucess:請(qǐng)求成功時(shí)的返回值 fail:請(qǐng)求失敗時(shí)的返回值 * */ - (void)netWorkType:(AKNetWorkType)netWorkType Signature:(NSString *)signature API:(NSString *)api Parameters:(NSDictionary *)parameters Success:(HttpSuccess)sucess Fail:(HttpErro)fail; @end
2> .m文件,導(dǎo)入頭文件AFNetworking.h 新建Manager 屬性并實(shí)現(xiàn)shareHttpManager類(lèi)方法
#import "AKNetPackegeAFN.h" #import "AFNetworking.h" @interface AKNetPackegeAFN() @property (nonatomic,strong) AFHTTPSessionManager *manager; @end @implementation AKNetPackegeAFN +(instancetype)shareHttpManager{ static dispatch_once_t onece = 0; static AKNetPackegeAFN *httpManager = nil; dispatch_once(&onece, ^(void){ httpManager = [[self alloc]init]; }); return httpManager; }
2,Get 與Post 方法的實(shí)現(xiàn)
使用時(shí)將后臺(tái)所給的證書(shū)轉(zhuǎn)換為 .cer格式 拖入項(xiàng)目根目錄中,在方法中進(jìn)行綁定即可例如后臺(tái)給的證書(shū)名為:Kuture.crt 收到證書(shū)后雙擊進(jìn)行安裝,然后打開(kāi)鑰匙串,將名為Kuture的證書(shū)右擊導(dǎo)出,選擇后綴為.cer 然后確定即可 如下圖所示:
-->
-->
-->
GET 與 POST 實(shí)現(xiàn)方法的封裝
- (void)netWorkType:(AKNetWorkType)netWorkType Signature:(NSString *)signature API:(NSString *)api Parameters:(NSDictionary *)parameters Success:(HttpSuccess)sucess Fail:(HttpErro)fail{ //開(kāi)啟證書(shū)驗(yàn)證模式 AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; //是否允許使用自簽名證書(shū) signature == nil ? (void)(securityPolicy.allowInvalidCertificates = NO):(securityPolicy.allowInvalidCertificates = YES); //是否需要驗(yàn)證域名 securityPolicy.validatesDomainName = NO; _manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:api]]; _manager.responseSerializer = [AFJSONResponseSerializer serializer]; _manager.securityPolicy = securityPolicy; _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/xml",@"text/json",@"text/plain",@"text/javascript",@"text/html", nil]; if (signature != nil){ __weak typeof(self) weakSelf = self; [_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) { //獲取服務(wù)器的 trust object SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust]; //導(dǎo)入自簽名證書(shū) NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"你的證書(shū)名字" ofType:@"cer"]; NSData *cerData = [NSData dataWithContentsOfFile:cerPath]; if (!cerData) { NSLog(@"==== .cer file is nil ===="); return 0; } NSArray *cerArray = @[cerData]; weakSelf.manager.securityPolicy.pinnedCertificates = cerArray; SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)cerData); NSCAssert(caRef != nil, @"caRef is nil"); NSArray *caArray = @[(__bridge id)(caRef)]; NSCAssert(caArray != nil, @"caArray is nil"); //將讀取到的證書(shū)設(shè)置為serverTrust的根證書(shū) OSStatus status = SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray); SecTrustSetAnchorCertificatesOnly(serverTrust, NO); NSCAssert(errSecSuccess == status, @"SectrustSetAnchorCertificates failed"); //選擇質(zhì)詢(xún)認(rèn)證的處理方式 NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; __autoreleasing NSURLCredential *credential = nil; //NSURLAuthenTicationMethodServerTrust質(zhì)詢(xún)認(rèn)證方式 if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { //基于客戶(hù)端的安全策略來(lái)決定是否信任該服務(wù)器,不信任則不響應(yīng)質(zhì)詢(xún) if ([weakSelf.manager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { //創(chuàng)建質(zhì)詢(xún)證書(shū) credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; //確認(rèn)質(zhì)詢(xún)方式 if (credential) { disposition = NSURLSessionAuthChallengeUseCredential; } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } else { //取消挑戰(zhàn) disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; } return disposition; }]; } if (netWorkType == 0){ [_manager GET:api parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (sucess){ sucess(responseObject); }else{ NSLog(@"鏈接異?;蚓W(wǎng)絡(luò)不存在"); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { fail(error); }]; }else if (netWorkType == 1){ [_manager POST:api parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (sucess){ sucess(responseObject); }else{ NSLog(@"鏈接異?;蚓W(wǎng)絡(luò)不存在"); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { fail(error); }]; } }
2 使用方法,在需要進(jìn)行數(shù)據(jù)獲取或傳遞的類(lèi)里面,直接導(dǎo)入頭文件 AKNetPackegeAFN.h ,并實(shí)現(xiàn)方法即可,如下所示:
//創(chuàng)建對(duì)象 //如果是自簽名證書(shū),使用前先到AKNetPackegeAFN相應(yīng)的方法里進(jìn)行證書(shū)的綁定(證書(shū)直接拖入項(xiàng)目中)即可 /* * netWorkType:請(qǐng)求方式 GET 或 POST signature:是否使用簽名證書(shū),是的話(huà)直接寫(xiě)入證書(shū)名字,否的話(huà)填nil api:請(qǐng)求的URL接口 parameters:請(qǐng)求參數(shù) sucess:請(qǐng)求成功時(shí)的返回值 fail:請(qǐng)求失敗時(shí)的返回值 * */ AKNetPackegeAFN *netHttps = [AKNetPackegeAFN shareHttpManager]; [netHttps netWorkType:請(qǐng)求類(lèi)型 Signature:證書(shū)名稱(chēng) API:請(qǐng)求URL Parameters:參數(shù) Success:^(id json) { NSLog(@"Json:%@",json); } Fail:^(NSError *error) { NSLog(@"Error:%@",error); }];
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- iOS實(shí)現(xiàn)電子簽名
- iOS mobileconfig配置文件進(jìn)行簽名的配置方法
- iOS 超級(jí)簽名之描述文件的實(shí)現(xiàn)過(guò)程
- iOS應(yīng)用腳本重簽名的實(shí)現(xiàn)方法
- iOS APP簽名機(jī)制原理詳解
- 詳解IOS微信上Vue單頁(yè)面應(yīng)用JSSDK簽名失敗解決方案
- Android和iOS包批量重簽名
- iOS安全防護(hù)系列之重簽名防護(hù)與sysctl反調(diào)試詳解
- iOS 基于AFNetworking下自簽名證書(shū)配置的方法
- iOS中的ipa重簽名(逆向必備)
- IOS 簽名錯(cuò)誤codesign failed with exit code 1解決方法
- ios的簽名機(jī)制詳解
相關(guān)文章
touchesBegan: withEvent: 不執(zhí)行解決
這篇文章主要介紹了touchesBegan: withEvent: 不執(zhí)行解決的相關(guān)資料,需要的朋友可以參考下2016-12-12iOS仿支付寶芝麻信用分?jǐn)?shù)儀表盤(pán)動(dòng)畫(huà)效果
這篇文章主要為大家詳細(xì)介紹了iOS仿支付寶芝麻信用分?jǐn)?shù)儀表盤(pán)動(dòng)畫(huà)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09iOS開(kāi)發(fā)之?dāng)r截URL轉(zhuǎn)換成本地路由模塊URLRewrite詳解
這篇文章主要給大家介紹了關(guān)于iOS開(kāi)發(fā)之?dāng)r截URL轉(zhuǎn)換成本地路由模塊URLRewrite的相關(guān)資料,這是最近在工作中遇到的一個(gè)需求,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起看看吧。2017-08-08iOS開(kāi)發(fā)存儲(chǔ)應(yīng)用程序Info.plist知識(shí)全面詳解
這篇文章主要為大家介紹了iOS開(kāi)發(fā)存儲(chǔ)應(yīng)用程序Info.plist知識(shí)全面詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06Objective-C實(shí)現(xiàn)自定義的半透明導(dǎo)航
這篇文章主要為大家詳細(xì)介紹了Objective-C實(shí)現(xiàn)自定義的半透明導(dǎo)航的相關(guān)資料,需要的朋友可以參考下2016-05-05iOS貝塞爾曲線畫(huà)哆啦A夢(mèng)的代碼實(shí)例
本篇文章主要介紹了iOS貝塞爾曲線畫(huà)哆啦A夢(mèng)的代碼實(shí)例,這里整理了詳細(xì)的代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-07-07