AFN中如何使用ip直接访问https网站

原文链接:https://github.com/AFNetworking/AFNetworking/issues/2954

项目开发需求使用DNS解析域名,获取IP发起HTTPS网络请求,通过IP直接访问网站,可以解决DNS劫持问题
  • 首先解决下怎么根据域名获取到IP,以下代码返回的就是IP值
 #pragma mark======== 域名解析
 + (NSString*)getIPWithHostName
{
// 这里的JHHostName就是我的域名
    const char *hostN= [JHHostName UTF8String];
    struct hostent* phot;
    
    @try {
        phot = gethostbyname(hostN);
        
    }
    @catch (NSException *exception) {
        return nil;
    }
    
    struct in_addr ip_addr;
    memcpy(&ip_addr, phot->h_addr_list[0], 4);
    char ip[20] = {0};
    inet_ntop(AF_INET, &ip_addr, ip, sizeof(ip));
    
    NSString* strIPAddress = [NSString stringWithUTF8String:ip];
    return strIPAddress;
}
  • 那么怎么解决IP直连发起HTTPS请求呢?

<1> 最直接的方式是允许无效的SSL证书,生产环境不建议使用;
<2> 一个需要部分重写AFN的方法.

  • 在Info.plist中添加NSAppTransportSecurity类型Dictionary,在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES.这些本来是用来解决iOS9下,允许HTTP请求访问网络的,当然作用不止这些.具体原因感兴趣的自行google.
  • 给 AFURLSessionManager 类添加新属性:
/** 可信任的域名,用于支持通过ip访问此域名下的https链接.
 Trusted domain, this domain for support via IP access HTTPS links.
 */
@property(nonatomic, strong) NSMutableArray * trustHostnames;
  • 给 AFURLSessionManager 实现的代理方法:
 - (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler

添加可信任的域名的相关逻辑代码:

 - (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;

    if (self.sessionDidReceiveAuthenticationChallenge) {
        disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
    } else {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
 #pragma mark============== 自己添加的
            SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
            
            /* 添加可信任的域名,以支持:直接使用ip访问特定https服务器.
             Add trusted domain name to support: direct use of IP access specific HTTPS server.*/
            for (NSString * trustHostname  in [self trustHostnames]) {
                serverTrust = AFChangeHostForTrust(serverTrust, trustHostname);
            }  
 #pragma mark-------------- 结束
            if ([self.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;
        }
    }

    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}
  • 参考Apple官方文档,实现自定义的添加可信域名的函数: AFChangeHostForTrust ,也是在这个类里添加
 #pragma mark============= 自定义
static inline SecTrustRef AFChangeHostForTrust(SecTrustRef trust, NSString * trustHostname)
{
    if ( ! trustHostname || [trustHostname isEqualToString:@""]) {
        return trust;
    }
    CFMutableArrayRef newTrustPolicies = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    SecPolicyRef sslPolicy = SecPolicyCreateSSL(true, (CFStringRef)trustHostname);
    CFArrayAppendValue(newTrustPolicies, sslPolicy);
 #ifdef MAC_BACKWARDS_COMPATIBILITY
    /* This technique works in OS X (v10.5 and later) */
    SecTrustSetPolicies(trust, newTrustPolicies);
    CFRelease(oldTrustPolicies);
    
    return trust;
#else
    /* This technique works in iOS 2 and later, or
     OS X v10.7 and later */
    
    CFMutableArrayRef certificates = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    
    /* Copy the certificates from the original trust object */
    CFIndex count = SecTrustGetCertificateCount(trust);
    CFIndex i=0;
    for (i = 0; i < count; i++) {
        SecCertificateRef item = SecTrustGetCertificateAtIndex(trust, i);
        CFArrayAppendValue(certificates, item);
    }
    
    /* Create a new trust object */
    SecTrustRef newtrust = NULL;
    if (SecTrustCreateWithCertificates(certificates, newTrustPolicies, &newtrust) != errSecSuccess) {
        /* Probably a good spot to log something. */
        
        return NULL;
    }
    
    return newtrust;
#endif
}
#pragma mark------------- 自定义结束
  • 使用AOP方法,重写 AFURLConnectionOperation 的trustHostnames属性,使用pod导入,pod 'Aspects'导入AOP框架
    注意:这些代码也要写入 AFURLSessionManager 的代理方法中:
 - (void)URLSession:(NSURLSession )session
didReceiveChallenge:(NSURLAuthenticationChallenge )challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandle
  • <a href="http://www.jianshu.com/p/addd4eac54ed">AOP编程参考文章</a>
   /* 使用AOP方式,指定可信任的域名, 以支持:直接使用ip访问特定https服务器.*/
            [AFURLSessionManager aspect_hookSelector:@selector(trustHostnames) withOptions:AspectPositionInstead usingBlock: ^(id<AspectInfo> info){
                __autoreleasing NSArray * trustHostnames = @[JHHostName];
                 NSInvocation *invocation = info.originalInvocation;
                [invocation setReturnValue:&trustHostnames];
            }error:NULL];
  • 最后一步检查自己的这个
 - (void)URLSession:(NSURLSession )session
didReceiveChallenge:(NSURLAuthenticationChallenge )challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandle

方法是否和我的一样:

 - (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;

    if (self.sessionDidReceiveAuthenticationChallenge) {
        disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
    } else {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
#pragma mark============== 自己添加的
            
            /* 使用AOP方式,指定可信任的域名, 以支持:直接使用ip访问特定https服务器.*/
            [AFURLSessionManager aspect_hookSelector:@selector(trustHostnames) withOptions:AspectPositionInstead usingBlock: ^(id<AspectInfo> info){
                __autoreleasing NSArray * trustHostnames = @[JHHostName];
                
                NSInvocation *invocation = info.originalInvocation;
                [invocation setReturnValue:&trustHostnames];
            }error:NULL];
            
            SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
            
            /* 添加可信任的域名,以支持:直接使用ip访问特定https服务器.
             Add trusted domain name to support: direct use of IP access specific HTTPS server.*/
            for (NSString * trustHostname  in [self trustHostnames]) {
                serverTrust = AFChangeHostForTrust(serverTrust, trustHostname);
            }
 #pragma mark-------------- 结束

            if ([self.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;
        }
    }
    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}
  • 到此我以为结束了,然而请求一直失败,我使用DNS解析出来的IP直接发起请求告诉证书验证失败状态码返回一直是 code= -999
    然后各种搞不通,后来猜测是域名被IP替换了而IP并没有配置证书,
    我尝试越过证书校验:
    // 用于越过验证https证书的代码
[_sessionManager.securityPolicy setAllowInvalidCertificates:YES];
[_sessionManager.securityPolicy setValidatesDomainName:NO];

上边代码是为了找原因,不要写入你的正式项目中哦!
这样是可以的,那么就确定了是IP的验证证书失败了,然而域名的证书验证是成功的,我直接用域名请求也是通的。

  • 接下来就是解决问题了,之前代理方法中我们已经添加了相关代码添加了可信任的域名,
    然后就是在你的网络请求发起之前要做的事情了,在发起网络请求前替换把我们在类里添加的属性数组中放入IP:
 /**
 POST网络请求
 */
 - (void)POST:(NSString *)url parameters:(id)params Success:(SuccessBlockType)successBlock failed:(FailedBlockType)failedBlock
{
// 将IP放入数组中
    NSArray * array = @[self.ipHostName];
// 给自定义添加的属性赋值
    _sessionManager.trustHostnames = [NSMutableArray arrayWithArray:array];
// 发起请求
    [_sessionManager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            DLog(@"请求URL:%@ 参数params:%@ 数据返回:%@",url,params,responseObject);
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failedBlock) {
            //            DLog(@"Error: %@", error);
            
            failedBlock(error);
        }
    }];
}

现在就可以实现我们的需求了。注意这个是修改的AFN的源码,你在更新SDK时需要做好备份。

大佬们给点个赞吧!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,049评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,478评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,109评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,097评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,115评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,280评论 1 279
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,748评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,398评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,553评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,440评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,487评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,176评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,750评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,821评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,049评论 1 257
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,559评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,150评论 2 341

推荐阅读更多精彩内容