刚踩的AFN配置Https证书的小坑

项目中使用的YTKNetwork,配置https证书的时候

YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
config.baseUrl = RootUrl;
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];//证书的路径
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
config.securityPolicy.pinnedCertificates = [NSSet setWithObject:certData];
config.securityPolicy.allowInvalidCertificates = YES;
config.securityPolicy.validatesDomainName = YES;

就是copy原来封装AFN时候的设置,原来设置的代码是这样的

NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];
NSData * certData =[NSData dataWithContentsOfFile:cerPath];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
securityPolicy.allowInvalidCertificates = YES ;
securityPolicy.validatesDomainName = YES ;
[securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
manger.securityPolicy = securityPolicy;

结果项目跑起来的时候,接口不通,打印错误
In order to validate a domain name for self signed certificates, you MUST use pinning.
这个错误的打印是在AFN的AFSecurityPolicy这个类里面打印的

- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
                  forDomain:(NSString *)domain
{
    if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
        // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
        //  According to the docs, you should only trust your provided certs for evaluation.
        //  Pinned certificates are added to the trust. Without pinned certificates,
        //  there is nothing to evaluate against.
        //
        //  From Apple Docs:
        //          "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
        //           Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
        NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
        return NO;
    }

就是因为我这种设置的时候SSLPinningMode这个属性默认是AFSSLPinningModeNone,正好满足了验证不通过条件了,所以
allowInvalidCertificates
validatesDomainName
SSLPinningMode
这三个属性设置起来有点矛盾,如果前两个都是YES了那SSLPinningMode就不能用默认的AFSSLPinningModeNone
反正就是不能满足这个验证方法里面的第一个if条件
就这样!

贴一篇iOS安全策略之HTTPS
[https://www.imooc.com/article/254196]

你可能感兴趣的:(刚踩的AFN配置Https证书的小坑)