码迷,mamicode.com
首页 > Web开发 > 详细

【原创】NSURLSession HTTPS Mutual Authentication

时间:2017-01-12 18:58:44      阅读:46      评论:0      收藏:0      [点我收藏+]

标签:methods   val   cal   position   base   使用   nconf   and   url   

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

标签:methods   val   cal   position   base   使用   nconf   and   url   

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!