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, );
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的更多相关文章

  1. [转] An Introduction to Mutual SSL Authentication

    1. Introduction Mutual SSL authentication or certificate based mutual authentication refers to two p ...

  2. 网络服务器之HTTPS服务

    import ssl, socket, time if __name__ == "__main__": context = ssl.SSLContext(ssl.PROTOCOL_ ...

  3. Configuring HTTP and HTTPS

    Configuring HTTP and HTTPS .NET Framework (current version)   Other Versions   WCF services and clie ...

  4. 服务器 apache配置https,http强制跳转https(搭建http与https共存)

    公司linux服务器上的nginx的已经改成https了,现在还剩下一个windows云服务器没配置. 环境 windows wampserver2.5 64位 1.腾讯云申请的ssl 包含三个文件: ...

  5. xmapp开启https

    在开发微信小程序的时候我们需要开启https本地测试,以下我们说明使用xmapp如何开启https访问 1. php中开启ssl 在php的配置文件中把openssl前面的注释去掉, 大概在配置文件的 ...

  6. sip user Authentication and 401

    https://www.vocal.com/sip-2/sip-user-authentication/ https://tools.ietf.org/html/rfc3261 SIP User Au ...

  7. Maven 搭建spring boot多模块项目(附源码),亲测可以,感谢原创

    原创地址:https://segmentfault.com/a/1190000005020589 我的DEMO码云地址,持续添加新功能: https://gitee.com/itbase/Spring ...

  8. kerberos (https://en.wikipedia.org/wiki/Kerberos_(protocol))

    Protocol[edit] Description[edit] The client authenticates itself to the Authentication Server (AS) w ...

  9. trust an HTTPS connection

    https://zh.wikipedia.org/wiki/传输安全协议 SSL协议客户端要收发几个握手信号: 发送一个“ClientHello”消息,内容包括:支持的协议版本,比如TLS1.0版,一 ...

随机推荐

  1. Error with mysqld_safe

    出处:http://bugs.mysql.com/bug.php?id=18403 Description: - I downloaded the binary file “Standard 5.0. ...

  2. JTAG应该如何接线

    下面是某个ARM9评估板的原理图: 注意: 1. Vref和Vtarget可以直接连在一起,由被调试板提供3.3V或5V电源: 2. nTRST,最好上拉: 3. TDI,最好上拉 4. TMS,最好 ...

  3. POJ2533 Longest Ordered Subsequence 【最长递增子序列】

    Longest Ordered Subsequence Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 32192   Acc ...

  4. 最佳新秀Java(22)——再次了解泛型

    仿制药Java SE 1.5新功能.通用自然是参数化类型.即操作数据类型被指定为一个参数.这样的参数类型可以在课堂上使用.创建的接口和方法,他们被称为通用类..泛型方法. Java语言引入泛型的优点是 ...

  5. 一键部署mono 免费空间

    一键部署mono 免费空间支持c# 再也不担心伙食费换空间了 一直以来 部署mono 都是很头疼的事情 因为是我在是不熟悉非win环境,今天偶然发现这个项目,挺好的,分享下 https://githu ...

  6. [置顶] c# 验证码生成

    今儿有一个任务是输出一串字符,要求用GDI画出于是: Bitmap bm = new Bitmap(200, 200);             Graphics g = Graphics.FromI ...

  7. Dynamics CRM JS的调试的弊端解决办法

    说道CRMJS的调试的博客,之前已经有人写过.很简单,和平常网站JS的调试过程大致相同. 但是Dynamics 中JS调试最麻烦的莫过于出错之后需要修改代码了.因为随着JS代码的修改,伴随着需要保存和 ...

  8. Python Learing(一):Basic Grammar

    装了python2.7,去图书馆借了python入门经典,暂且简单写下学习笔记,以供自己回忆 学习笔记(一)主要是基础语法部分: 1.python中数字以及字符串的使用; 2.输入与输出语句; 3.逻 ...

  9. Google C++测试框架系列:入门

    Google C++测试框架系列:入门 原始链接:V1_6_Primer 注 GTest或者Google Test: Google的C++测试框架. Test Fixtures: 这个词实在找不到对应 ...

  10. MVC几种传值方式

    一,Model public class Course { public int Id { get; set; } public string Name { get; set; } } public ...