深入理解HTTPS及在iOS系统中适配HTTPS类型网络请求(四)

简介: 深入理解HTTPS及在iOS系统中适配HTTPS类型网络请求

二、关于NSURLAuthenticationChallenge相关类


   我们在实现URLSession的认证协议方法时,会接收到一个NSURLAuthenticationChallenge类型的参数。简单理解,这个参数就是服务端发起的一个验证挑战,客户端需要根据挑战的类型提供相应的挑战凭证。当然,挑战凭证不一定都是进行HTTPS证书的信任,也可能是需要客户端提供用户密码或者提供双向验证时的客户端证书。当这个挑战凭证被验证通过时,请求便可以继续顺利进行。NSURLAuthenticationChallenge类对象中有一个sender代理实例,开发者通过这个实例来可控采用怎样的验证方式。解析如下:


//使用凭证进行验证

- (void)useCredential:(NSURLCredential *)credential forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

//试图不提供凭证继续请求

- (void)continueWithoutCredentialForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

//取消凭证验证

- (void)cancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

//使用默认提供的凭证行为

- (void)performDefaultHandlingForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

//拒绝当前提供的受保护控件并且尝试不提供凭证继续请求

- (void)rejectProtectionSpaceAndContinueWithChallenge:(NSURLAuthenticationChallenge *)challenge;

可以看到,上面的协议方法中如果要进行凭证的验证,需要客户端提供一个凭证对象NSURLCredential。这个类可以简单理解为客户端创建的凭证信息,解析如下:


//通过用户名和密码进行凭证的创建

- (instancetype)initWithUser:(NSString *)user password:(NSString *)password persistence:(NSURLCredentialPersistence)persistence;

//同上

+ (NSURLCredential *)credentialWithUser:(NSString *)user password:(NSString *)password persistence:(NSURLCredentialPersistence)persistence;

//用户名属性 只读

@property (nullable, readonly, copy) NSString *user;

//密码属性 只读

@property (nullable, readonly, copy) NSString *password;

//是否有密码 只读

@property (readonly) BOOL hasPassword;

//通过客户端提供证书进行双向验证

- (instancetype)initWithIdentity:(SecIdentityRef)identity certificates:(nullable NSArray *)certArray persistence:(NSURLCredentialPersistence)persistence NS_AVAILABLE(10_6, 3_0);

//同上

+ (NSURLCredential *)credentialWithIdentity:(SecIdentityRef)identity certificates:(nullable NSArray *)certArray persistence:(NSURLCredentialPersistence)persistence NS_AVAILABLE(10_6, 3_0);

//创建证书信任凭证 用户自签名的HTTPS请求

- (instancetype)initWithTrust:(SecTrustRef)trust NS_AVAILABLE(10_6, 3_0);

//同上

+ (NSURLCredential *)credentialForTrust:(SecTrustRef)trust NS_AVAILABLE(10_6, 3_0);

上面方法中的NSURLCredentialPersistence枚举用来设置凭证的存储方式,解析如下:


typedef NS_ENUM(NSUInteger, NSURLCredentialPersistence) {

   NSURLCredentialPersistenceNone,  //不保存

   NSURLCredentialPersistenceForSession, //在本URLSession中有效

   NSURLCredentialPersistencePermanent, //保存在钥匙串中 ,永久有效

   NSURLCredentialPersistenceSynchronizable NS_ENUM_AVAILABLE(10_8, 6_0) //永久有效 并且被所有APPID设备共享

};

三、使用AFNetworking进行自签名证书HTTPS请求的认证


   使用AFNetworking也可以很方便的进行自签名证书的认证,还以上一节博客搭建的HTTPS环境为例,示例代码如下:


-(void)afHttps{

   NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://localhost:8080/users"]];

   AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

   //    securityPolicy.allowInvalidCertificates = YES;//是否允许使用自签名证书

   securityPolicy.validatesDomainName = NO;//是否需要验证域名,默认YES

 

   AFHTTPSessionManager *_manager = [AFHTTPSessionManager manager];

   _manager.responseSerializer = [AFHTTPResponseSerializer serializer];

   _manager.securityPolicy = securityPolicy;

   //设置超时

   [_manager.requestSerializer willChangeValueForKey:@"timeoutinterval"];

   _manager.requestSerializer.timeoutInterval = 20.f;

   [_manager.requestSerializer didChangeValueForKey:@"timeoutinterval"];

   _manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringCacheData;

   _manager.responseSerializer.acceptableContentTypes  = [NSSet setWithObjects:@"application/xml",@"text/html",@"text/plain",@"application/json",nil];

   [_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *_credential) {

     

       SecTrustRef serverTrust = [[challenge protectionSpace] serverTrust];

       /**

        *  导入多张CA证书

        */

       NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];//自签名证书

       NSData* caCert = [NSData dataWithContentsOfFile:cerPath];

       NSArray *cerArray = @[caCert];

       _manager.securityPolicy.pinnedCertificates = cerArray;

       SecCertificateRef caRef = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCert);

       NSArray *caArray = @[(__bridge id)(caRef)];

     

       SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)caArray);

       SecTrustSetAnchorCertificatesOnly(serverTrust,NO);

       NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;

       __autoreleasing NSURLCredential *credential = nil;

       if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

           if ([_manager.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;

   }];

   [[_manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

       NSLog(@"%@,%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding],error);

   }]resume];

}

目录
相关文章
|
10月前
|
iOS开发
Cisco Catalyst 9800 Wireless Controller, IOS XE Release 17.17.1 ED - 思科无线控制器系统软件
Cisco Catalyst 9800 Wireless Controller, IOS XE Release 17.17.1 ED - 思科无线控制器系统软件
346 9
Cisco Catalyst 9800 Wireless Controller, IOS XE Release 17.17.1 ED - 思科无线控制器系统软件
|
5月前
|
安全 5G 语音技术
Cisco ASR 9000 Router IOS XR Release 7.11.2 MD - ASR 9000 系列聚合服务路由器系统软件
Cisco ASR 9000 Router IOS XR Release 7.11.2 MD - ASR 9000 系列聚合服务路由器系统软件
287 4
Cisco ASR 9000 Router IOS XR Release 7.11.2 MD - ASR 9000 系列聚合服务路由器系统软件
|
5月前
|
安全 Linux 虚拟化
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
336 3
Cisco IOS XRv 9000 Router IOS XR Release 7.11.2 MD - 思科 IOS XR 网络操作系统
|
云安全 安全 Cloud Native
Cisco Catalyst 8000 Series IOS XE 17.18.1a ED 发布 - 思科边缘平台系列系统软件
Cisco Catalyst 8000 Series IOS XE 17.18.1a ED - 思科边缘平台系列系统软件
186 0
|
运维 监控 安全
Cisco ISR 4000 Series IOS XE 17.18.1a ED 发布 - 思科 4000 系列集成服务路由器 IOS XE 系统软件
Cisco ISR 4000 Series IOS XE 17.18.1a ED - 思科 4000 系列集成服务路由器 IOS XE 系统软件
235 0
|
人工智能 监控 安全
思科 Catalyst 9000 交换产品系列 IOS XE 系统软件 17.18.1 ED
Cisco Catalyst 9000 Series Switches, IOS XE Release 17.18.1 ED
225 0
|
12月前
|
机器学习/深度学习 数据采集 算法
基于MobileNet深度学习网络的MQAM调制类型识别matlab仿真
本项目基于Matlab2022a实现MQAM调制类型识别,使用MobileNet深度学习网络。完整程序运行效果无水印,核心代码含详细中文注释和操作视频。MQAM调制在无线通信中至关重要,MobileNet以其轻量化、高效性适合资源受限环境。通过数据预处理、网络训练与优化,确保高识别准确率并降低计算复杂度,为频谱监测、信号解调等提供支持。
|
安全 Android开发 数据安全/隐私保护
深入探索Android与iOS系统安全性的对比分析
在当今数字化时代,移动操作系统的安全已成为用户和开发者共同关注的重点。本文旨在通过比较Android与iOS两大主流操作系统在安全性方面的差异,揭示两者在设计理念、权限管理、应用审核机制等方面的不同之处。我们将探讨这些差异如何影响用户的安全体验以及可能带来的风险。
944 21
|
机器学习/深度学习 算法 数据安全/隐私保护
基于深度学习网络的宝石类型识别算法matlab仿真
本项目利用GoogLeNet深度学习网络进行宝石类型识别,实验包括收集多类宝石图像数据集并按7:1:2比例划分。使用Matlab2022a实现算法,提供含中文注释的完整代码及操作视频。GoogLeNet通过其独特的Inception模块,结合数据增强、学习率调整和正则化等优化手段,有效提升了宝石识别的准确性和效率。
|
iOS开发
iOS调用系统通讯录
iOS调用系统通讯录
304 0
iOS调用系统通讯录