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
   /* 使用AOP方式,指定可信任的域名, 以支持:直接使用ip访问特定https服务器.*/
            [AFURLSessionManager aspect_hookSelector:@selector(trustHostnames) withOptions:AspectPositionInstead usingBlock: ^(id 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 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时需要做好备份。

大佬们给点个赞吧!

你可能感兴趣的:(AFN中如何使用ip直接访问https网站)