深入理解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];

}

目录
相关文章
|
3月前
|
机器学习/深度学习 算法 机器人
【PID】基于人工神经网络的PID控制器,用于更好的系统响应研究(Matlab&Simulink代码实现)
【PID】基于人工神经网络的PID控制器,用于更好的系统响应研究(Matlab&Simulink代码实现)
365 15
|
1月前
|
安全 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 系列聚合服务路由器系统软件
195 4
Cisco ASR 9000 Router IOS XR Release 7.11.2 MD - ASR 9000 系列聚合服务路由器系统软件
|
1月前
|
Ubuntu 网络协议 网络安全
解决Ubuntu系统的网络连接问题
以上步骤通常可以帮助解决大多数Ubuntu系统的网络连接问题。如果问题仍然存在,可能需要更深入的诊断,或考虑联系网络管理员或专业技术人员。
436 18
|
30天前
|
机器学习/深度学习 大数据 关系型数据库
基于python大数据的青少年网络使用情况分析及预测系统
本研究基于Python大数据技术,构建青少年网络行为分析系统,旨在破解现有防沉迷模式下用户画像模糊、预警滞后等难题。通过整合多平台亿级数据,运用机器学习实现精准行为预测与实时干预,推动数字治理向“数据驱动”转型,为家庭、学校及政府提供科学决策支持,助力青少年健康上网。
|
1月前
|
监控 安全 网络协议
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
310 1
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
|
2月前
|
机器学习/深度学习 传感器 算法
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
195 2
|
3月前
|
安全 KVM 虚拟化
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
208 2
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
|
3月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
227 18
|
1月前
|
机器学习/深度学习 分布式计算 Java
Java与图神经网络:构建企业级知识图谱与智能推理系统
图神经网络(GNN)作为处理非欧几里得数据的前沿技术,正成为企业知识管理和智能推理的核心引擎。本文深入探讨如何在Java生态中构建基于GNN的知识图谱系统,涵盖从图数据建模、GNN模型集成、分布式图计算到实时推理的全流程。通过具体的代码实现和架构设计,展示如何将先进的图神经网络技术融入传统Java企业应用,为构建下一代智能决策系统提供完整解决方案。
281 0

热门文章

最新文章

下一篇
oss云网关配置