【原創】NSURLSession HTTPS Mutual Authentication,nsurlsessionmutual

來源:互聯網
上載者:User

【原創】NSURLSession HTTPS Mutual Authentication,nsurlsessionmutual

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獲得的認證資料進行比對,如果判斷為同一認證,則響應挑戰;特別要注意的是,協議回調會觸發兩次,分別為以上兩種驗證挑戰,如有其它類型挑戰則取消本次驗證

 

各位大神如有好的經驗希望分享出來~我也是在學習中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.