我正在尝试使用NSURLSession
在iOS中实施https客户端证书身份验证。这就是我在做的事情:
-(void) httpPostWithCustomDelegate :(NSDictionary *) params
{
NSString *ppyRequestURL = [NSString stringWithFormat:@"%@/fetchcountryCities", PPBaseURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:ppyRequestURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
Log(@"ASDAD");
}];
[postDataTask resume];
}
我在挑战处理程序中提供客户端证书,如下所示:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
NSURLCredential *credential = [self provideClientCertificate];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
}
以下是我加载客户端证书的方式,
- (SecIdentityRef)findClientCertificate {
SecIdentityRef clientCertificate = NULL;
if (clientCertificate) {
CFRelease(clientCertificate);
clientCertificate = NULL;
}
NSString *pkcs12Path = [[NSBundle mainBundle] pathForResource:@"johndoe" ofType:@"p12"];
NSData *pkcs12Data = [[NSData alloc] initWithContentsOfFile:pkcs12Path];
CFDataRef inPKCS12Data = (__bridge CFDataRef)pkcs12Data;
CFStringRef password = CFSTR("password");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = NULL;
OSStatus err = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items);
CFRelease(optionsDictionary);
CFRelease(password);
if (err == errSecSuccess && CFArrayGetCount(items) > 0) {
CFDictionaryRef pkcsDict = CFArrayGetValueAtIndex(items, 0);
SecTrustRef trust = (SecTrustRef)CFDictionaryGetValue(pkcsDict, kSecImportItemTrust);
if (trust != NULL) {
clientCertificate = (SecIdentityRef)CFDictionaryGetValue(pkcsDict, kSecImportItemIdentity);
CFRetain(clientCertificate);
}
}
if (items) {
CFRelease(items);
}
return clientCertificate;
}
- (NSURLCredential *)provideClientCertificate {
SecIdentityRef identity = [self findClientCertificate];
if (!identity) {
return nil;
}
SecCertificateRef certificate = NULL;
SecIdentityCopyCertificate (identity, &certificate);
const void *certs[] = {certificate};
CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL);
NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray *)certArray persistence:NSURLCredentialPersistencePermanent];
CFRelease(certArray);
return credential;
}
现在,当调用API时,我收到了这个错误:
错误域= NSURLErrorDomain代码= -1005“网络连接丢失。” UserInfo = {NSUnderlyingError = 0x7f8428df4d40 {错误域= kCFErrorDomainCFNetwork代码= -1005“(null)”UserInfo = {_ kCFStreamErrorCodeKey = -4,_kCFStreamErrorDomainKey = 4}}
我在模拟器和设备上遇到同样的错误。我完全卡住了。不知道这里出了什么问题。
*****更新***** 我确实检查了Charles代理以了解更多细节。令我惊讶的是,当我将客户端证书添加到charles代理时,我收到了来自服务器的响应,所以我错过了plist中的一些设置或加载p12的问题?
从plist设置,
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>test.mydomain.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSRequiresCertificateTransparency</key>
<false/>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<false/>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<true/>
</dict>
</dict>
</dict>
答案 0 :(得分:0)
乍看之下,我发现了三个问题:
您在没有提供请求正文的情况下发出了POST请求。这可能会导致请求在没有连接到服务器的情况下立即失败。
您所写的服务器信任处理通过告诉操作系统盲目信任它(我认为),有效地消除了您从TLS获得的任何保护。
你应该A.告诉NSURLSession在服务器信任案例中执行默认处理,或者B.自己检查证书,然后然后告诉它使用证书。
您的身份仅包含客户端证书,而不包括服务器信任它所需的任何中间证书。
您可能应该使用您找到的第一个标识合并这两个方法,但是将您在标识文件中找到的每个证书都添加到证书数组中(可能还有客户端证书本身,但我依旧回忆起来)你不应该把它添加到那里;尝试两种方式,看看哪一种失败了。
请注意,如果您知道没有任何用户&#39;身份将拥有证书链,然后第三个可能并不重要。