苹果公司在iOS9以后开启了HTTPS请求,并且在2017年开始强制HTTPS,我们也可以利用白名单来设置部分域名http请求,下面根据两种情况为大家分别介绍客户端需要做的。
方法一:SSL证书验证
一、将crt证书转换成cer证书方法有两种
方法1.使用openssl 进行转换
openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der
方法2.通过安装crt文件,电脑导出
1)先打开“钥匙串访问”
2)选中你安装的crt文件证书,选择“文件”--》“导出项目”
二、AFNetworking 对数据进行https ssl加密
1、导入证书并添加设置方法
+ (AFSecurityPolicy*)customSecurityPolicy
{
// /先导入证书
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"hgcang" ofType:@"cer"];//证书的路径
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
// AFSSLPinningModeCertificate 使用证书验证模式
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
// allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
// 如果是需要验证自建证书,需要设置为YES
securityPolicy.allowInvalidCertificates = YES;
//validatesDomainName 是否需要验证域名,默认为YES;
//假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
//置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
//如置为NO,建议自己添加对应域名的校验逻辑。
securityPolicy.validatesDomainName = NO;
securityPolicy.pinnedCertificates = @[certData];
return securityPolicy;
}
2、请求网络时候进行加密验证(引用上面方法)
+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
// 2.申明返回的结果是text/html类型
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
// 加上这行代码,https ssl 验证。
//[mgr setSecurityPolicy:[self customSecurityPolicy]];
// 3.发送POST请求
[mgr POST:url parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObj) {
if (success) {
success(responseObj);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
}
方法二:白名单设置单个http域名
解决方案:我们可以通过NSExceptionDomains设置白名单的方式来针对特定的域名开放HTTP内容来通过审核。可以简单理解成,把不支持https协议的接口设置成http的接口。
操作:
1)在项目info.plist中添加一个Key:App Transport Security Settings,类型为
Dictionary;
2)在其内添加一个Key: Exception Domains,类型为Dictionary;
3)在Exception Domains内添加要支持的域,其中域作为Key,类型为Dictionary;
4)每个域下面需要设置3个属性:类型为Boolean;
NSIncludesSubdomains YES
NSExceptionRequiresForwardSecrecy NO
NSExceptionAllowsInsecureHTTPLoads YES
注意:每个需添加的域都需要设置此三个属性。如果请求的网络图片是HTTP,也是需要设置的图片的域。