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. leetcode第39题--Combination Sum II

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  2. StringTokenizer使用类

    StringTokenizer它被用来分离String应用类别.当量VB的split功能. 1.构造函数 public StringTokenizer(String str) public Strin ...

  3. JDK6、Oracle11g、Weblogic10 For Linux64Bit安装部署说明

    JDK6.Oracle11g.Weblogic10 For Linux64Bit安装部署说明 项目编号 编写人 成 编写日期 2013/07/29 审核 修订说明 目录 JDK6.ORACLE11G. ...

  4. rsync服务器

    转自:http://www.mike.org.cn/blog/index.php?load=read&id=639###pp=0 [rsync实现网站的备份,文件的同步,不同系统的文件的同步, ...

  5. EF codefirst+mvc4+bootstrap+autofac+ddd 系统共享 祝大家新年开心搬砖

    博客园的博友新年好,小弟在此给大伙拜了晚年,感谢一直以来的支持. 在过去的一年,从博客园有400多ASP.NET MVC爱好者加入本人的群,本人在此很感激,并勉励大家一起学习奋斗. 希望在新的一年,继 ...

  6. 用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的Code First迁移和部署

    用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的Code First迁移和部署 这是微软官方SignalR 2.0教程Getting Started with En ...

  7. Linq无聊练习系列8---开放式并发事务,null和 DateTime,string操作练习

    /*********************开放式并发事务,null和 DateTime,string操作练习**********************************/ //所谓并发,就是 ...

  8. C#中几个经常犯的错误总汇

    在我们平常编程中,时间久了有时候会形成一种习惯性的思维方式,形成固有的编程风格,但是有些地方是需要斟酌的,即使是一个很小的错误也可能会导致昂贵的代价,要学会善于总结,从错误中汲取教训,尽量不再犯同样错 ...

  9. ToolBox Analysis & Design

    话说小菜过做已近3年,虽出身PHP后项目大多涉及.net,系统也做得比较繁杂,从常见的CMS,企业OA,ERP,也涉及到电商系统的开发定制,爬虫,工具不一而足,其中web系统居多. 由于表现良好,时常 ...

  10. Push Notification总结系列(一)

    Notification系列概括: 1.Push Notification简介和证书说明及生成配置 2.Push Notification的iOS处理代码和Provider详解 3.Push Noti ...