服务端配置

nginx关键配置例如以下:

listen       443;
server_name localhost;
ssl on;
ssl_certificate /usr/local/opt/nginx/certificates/server.cer;
ssl_certificate_key /usr/local/opt/nginx/certificates/server.key.pem;
ssl_client_certificate /usr/local/opt/nginx/certificates/ca.cer;
ssl_verify_client on;

ssl开启https

ssl_certificate是服务端证书的路径,ssl_certificate_key是服务端私钥的路径

ssl_verify_client是配置双向认证(client certificate)

ssl_client_certificate是签发客户端证书的根证书

为什么是根证书。由于能够签发非常多client证书,仅仅要是由该根证书签发的,服务端都视为认证通过

配置完毕以后,一般须要把80port的http请求跳转到443port,否则用户能够通过80port以http方式訪问,就失去了安全保护的意义

client代码

在网上找了非常多ios client certificate的帖子,要么是代码不全。要么是非常老的帖子,还是用的NSURLConnection,delegate method都deprecated了,最后找了一个代码片段,改了一下

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURL *url = [NSURL URLWithString:@"https://localhost/svc/portal/setting"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"GET"]; NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", message);
}]; [task resume];

上面的代码片段,是用NSURLSessionDataTask发起https请求。在ssl握手阶段,会调用2次以下的delegate method

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
NSString *method = challenge.protectionSpace.authenticationMethod;
NSLog(@"%@", method); if([method isEqualToString:NSURLAuthenticationMethodServerTrust]){ NSString *host = challenge.protectionSpace.host;
NSLog(@"%@", host); NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
return;
} NSString *thePath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"p12"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (CFDataRef)CFBridgingRetain(PKCS12Data);
SecIdentityRef identity; // 读取p12证书中的内容
OSStatus result = [self extractP12Data:inPKCS12Data toIdentity:&identity];
if(result != errSecSuccess){
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
return;
} SecCertificateRef certificate = NULL;
SecIdentityCopyCertificate (identity, &certificate); const void *certs[] = {certificate};
CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, certs, 1, NULL); NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:(NSArray*)CFBridgingRelease(certArray) persistence:NSURLCredentialPersistencePermanent]; completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
} -(OSStatus) extractP12Data:(CFDataRef)inP12Data toIdentity:(SecIdentityRef*)identity { OSStatus securityError = errSecSuccess; CFStringRef password = CFSTR("the_password");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password }; CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import(inP12Data, options, &items); if (securityError == 0) {
CFDictionaryRef ident = CFArrayGetValueAtIndex(items,0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity);
*identity = (SecIdentityRef)tempIdentity;
} if (options) {
CFRelease(options);
} return securityError;
}

上面的代码片段。即拷即用,希望能有所帮助。

这种方法会被调用2次,第一次是ios app验证server的阶段,第二次是server验证ios app的阶段。即client certificate。关键是每一个阶段的校验完毕以后。要调用completionHandler方法。

网上的大部分帖子都是

[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];

这行代码是无效的

nginx与ios实现https双向认证的更多相关文章

  1. HTTPS 双向认证构建移动设备安全体系

    HTTPS 双向认证构建移动设备安全体系 对于一些高安全性要求的企业内项目,我们有时希望能够对客户端进行验证.这个时候我们可以使用Https的双向认证机制来实现这个功能. 单向认证:保证server是 ...

  2. Tomcat 配置 HTTPS双向认证

    Tomcat 配置 HTTPS 双向认证指引说明: � 本文档仅提供 Linux 操作系统下的指引 � 在阅读本指引前请您在 Linux 部署 JDK 和 Tomcatserver为了 Tomcat ...

  3. httpd设置HTTPS双向认证

    去年用tomcat.jboss配置过HTTPS双向认证,那时候主要用的是JDK自带的keytool工具.这次是用httpd + openssl,区别比较大 在网上搜索了很多文章,发现全面介绍的不多,或 ...

  4. Https双向认证Android客户端配置

    Https .cer证书转换为BKS证书 公式https://blog.csdn.net/zww986736788/article/details/81708967 keytool -importce ...

  5. Android Https双向认证 + GRPC

    keywords:android https 双向认证android GRPC https 双向认证 ManagedChannel channel = OkHttpChannelBuilder.for ...

  6. 双向认证 HTTPS双向认证

    [微信支付]微信小程序支付开发者文档 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3 HTTPS双向认证使用说明 ...

  7. https双向认证訪问管理后台,採用USBKEY进行系统訪问的身份鉴别,KEY的证书长度大于128位,使用USBKEY登录

    近期项目需求,须要实现用USBKEY识别用户登录,採用https双向认证訪问管理后台管理界面,期间碰到过一些小问题,写出来给大家參考下. 1:前期准备工作 USBKEY 硬件:我买的是飞天诚信 epa ...

  8. nodejs之https双向认证

    说在前面 之前我们总结了https的相关知识,如果不懂可以看我另一篇文章:白话理解https 有关证书生成可以参考:自签证书生成 正题 今天使用nodejs来实现https双向认证 话不多说,直接进入 ...

  9. SpringBoot服务间使用自签名证书实现https双向认证

    SpringBoot服务间使用自签名证书实现https双向认证 以服务server-one和server-two之间使用RestTemplate以https调用为例 一.生成密钥 需要生成server ...

随机推荐

  1. javascript 多行字符串

    javascript 字符串多行 平时一般使用 字符串+,或者[].join('')的方式 同事推荐了这样的形式 ExceptionDivHtml="<div class='gameI ...

  2. [Python]豆瓣用户读书短评下载工具

    简介 朋友问我能不能做一个下载他在豆瓣读书上的短评的工具,于是就做了这个“豆瓣用户读书短评下载工具”. GitHub链接:https://github.com/xiaff/dbc-downloader ...

  3. C语言struct类型

    在实际问题中,一组数据往往具有不同的数据类型.例如, 在学生登记表中,姓名应为字符型:学号可为整型或字符型: 年龄应为整型:性别应为字符型:成绩可为整型或实型. 显然不能用一个数组来存放这一组数据. ...

  4. J2SE知识点摘记(七)

    1.        枚举的用法 enum 枚举名{枚举值表标};例子:"enum weekday{sun,mon,tue,wed,fri,sat}a,b,c;" For循环语句中使 ...

  5. 【每天一个Linux命令】12. Linux中which命令的用法

    which  用来查看可执行文件的位置. 1.命令格式: which 可执行文件名称 2.命令功能: which指令会在PATH变量指定的路径中,搜索某个系统命令的位置,并且返回第一个搜索结果. 3. ...

  6. mongodb remove删除文档的用法

    在看<mongoDB权威指南>中,在删除文档时,出现问题: 书中介绍:采用db.foo.remove()命令则可以删除foo集合中所有的文档,但是在执行该命令时,shell客户端却报错. ...

  7. Android之单击返回键两次退出

    private static Boolean isExit = false;        private static Boolean hasTask = false;        Timer t ...

  8. VBA 开发学习--基础语法

    MsgBox "开始学习VBA" '提示框 Dim str As String '声明str变量是string类型 Let str = "一起来看流星雨" '给 ...

  9. C++ ofstream和ifstream

    ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间; 在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O, ...

  10. 前端新人学习笔记-------html/css/js基础知识点

    即将毕业的软件工程大学生一枚,秋季招聘应聘的是Android,今年来到公司实习,要求做前端开发,所以一切只有现学,现在根据视频来学习,然后开这个博客记录一下自己的学习过程,废话不多说,开写. 4月6日 ...