原创NSURLSession HTTPS Mutual Authentication

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原创NSURLSession HTTPS Mutual Authentication相关的知识,希望对你有一定的参考价值。

1.引入<NSURLSessionDelegate>协议

2.登录验证请求

-(void)authenticate
{
    NSURL *url = [NSURL URLWithString:authAddress];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    NSString *userString = @"name:password";
    NSData *userData = [userString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [userData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    [request setValue:[NSString stringWithFormat:@"Basic %@",base64String] forHTTPHeaderField:@"Authorization"];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    [task resume];
}

3.NSURLSessionDelegate回调

#pragma mark -- NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate])//Client Authentication
    {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:@"name" password:@"password" persistence:NSURLCredentialPersistenceForSession];
        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
    else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])//Server Authentication
    {
        SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
        SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
        NSData *serverData = (__bridge_transfer NSData*)SecCertificateCopyData(serverCertificate);
        NSData *localData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cert" ofType:@"cer"]];
        if ((!localData) || [serverData isEqualToData:localData])
        {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
            [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        }
        else
        {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
        }
    }
    else
    {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil);
    }
}

注意:NSURLAuthenticationMethodClientCertificate为客户端证书验证,有p12证书的话需要使用此证书进行认证,方法参考此文章;NSURLAuthenticationMethodServerTrust为服务端验证,我们需要用本地证书与服务端返回的挑战的serverTrust获得的证书数据进行比对,如果判断为同一证书,则响应挑战;特别要注意的是,协议回调会触发两次,分别为以上两种验证挑战,如有其它类型挑战则取消本次验证

 

各位大神如有好的经验希望分享出来~我也是在学习中

以上是关于原创NSURLSession HTTPS Mutual Authentication的主要内容,如果未能解决你的问题,请参考以下文章

Paypal IPN - 无法打开套接字 - OVH mutu

NSURLSession http转Https

具有大量文件和 wsse HTTPS 标头的后台 NSURLSession 用于身份验证

NSURLSession学习

NSURLSession 的 IOS9 SSL 错误

NSURLSession 后台断点下载