小编Vla*_*mir的帖子

iOS 12:使用URLSession验证本地证书

我在局域网中有一项服务,该服务使用自定义签名证书进行HTTPS连接。我有证书(cer,p12,der等),它们都可以相互转换。问题是,收到NSURLAuthenticationMethodClientCertificate的挑战时,我应该在didReceiveChallenge中写什么?

不,我不想使用NSAllowsArbitraryLoads,那将是一个安全漏洞。到目前为止,我将要使用NSAllowsLocalNetworking。

- (void)URLSession:(NSURLSession*)session
    didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge
      completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential* _Nullable))completionHandler {
    bool handled = false;

    // Always trust any server name (which is an IP address actually)
    NSLog(@"method: %@", challenge.protectionSpace.authenticationMethod);
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        SecTrustRef trust = challenge.protectionSpace.serverTrust;
        if (trust != nullptr) {
            completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:trust]);
            handled = true;
        }
    }
    else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate) {
        NSString* cerFile = [NSBundle.mainBundle pathForResource:@"dev" ofType:@"der"];
        NSData* data = [NSData dataWithContentsOfFile:cerFile];
        SecCertificateRef cert = SecCertificateCreateWithData(nil, (CFDataRef)data);


        // here I have to somehow validate …
Run Code Online (Sandbox Code Playgroud)

objective-c ssl-certificate ios

5
推荐指数
1
解决办法
111
查看次数

标签 统计

ios ×1

objective-c ×1

ssl-certificate ×1