1.如果想跳过ssl验证的话 AFHTTPSessionManager * client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];[[client securityPolicy] setAllowInvalidCertificates:YES]; 2.加入ssl证书 一般来讲如果app用了web service ,
1.如果想跳过ssl验证的话
AFHTTPSessionManager * client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];[[client securityPolicy] setAllowInvalidCertificates:YES];
2.加入ssl证书
一般来讲如果app用了web service , 我们需要防止数据嗅探来保证数据安全.通常的做法是用ssl来连接以防止数据抓包和嗅探
其实这么做的话还是不够的.我们还需要防止中间人攻击(不明白的自己去百度)。攻击者通过伪造的ssl证书使app连接到了伪装的假冒的服务器上,这是个严重的问题!
那么如何防止中间人攻击呢?
首先web服务器必须提供一个ssl证书,需要一个 .crt 文件,然后设置app只能连接有效ssl证书的服务器。
在开始写代码前,先要把 .crt 文件转成 .cer 文件,然后在加到xcode 里面
openssl x509 -in 你的证书.crt -out 你的证书.cer -outform derCopier après la connexion
如果你用的是NSURLConnection,你需要这样检查证书,必须添加一个 NSURLConnectionDelegate
- (<span>void</span>)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
用 AFNetworking 2.x的话就简单多了,只需要添加一个AFSecurityPolicy
和 setAFHTTPRequestOperationManager
要经常用的话,推荐写一个方法,然后以后用就可以复制黏贴了
- (AFSecurityPolicy*<span>)customSecurityPolicy { </span><span>/*</span><span>*** SSL Pinning ***</span><span>*/</span><span> NSString </span>*cerPath = [[NSBundle mainBundle] pathForResource:<span>@"你的证书</span><span>"</span> ofType:<span>@"</span><span>cer</span><span>"</span><span>]; NSData </span>*certData =<span> [NSData dataWithContentsOfFile:cerPath]; AFSecurityPolicy </span>*securityPolicy =<span> [[AFSecurityPolicy alloc] init]; [securityPolicy setAllowInvalidCertificates:NO]; [securityPolicy setPinnedCertificates:@[certData]]; [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate]; </span><span>/*</span><span>*** SSL Pinning ***</span><span>*/</span> <span>return</span><span> securityPolicy; }</span>
然后在管理器里这么设置
AFHTTPRequestOperationManager *manager =<span> [AFHTTPRequestOperationManager manager]; </span><span>/*</span><span>*** SSL Pinning ***</span><span>*/</span><span> [manager setSecurityPolicy:[self customSecurityPolicy]]; </span><span>/*</span><span>*** SSL Pinning ***</span><span>*/</span><span> [manager GET:@"网站的url" parameters:</span><span>params</span> success:^(AFHTTPRequestOperation *operation, NSDictionary*<span> responseObject) { </span><span>//</span><span>这里是你自己的代码了</span> } failure:^(AFHTTPRequestOperation *operation, NSError *<span>error) { </span><span>//</span><span>注释同上</span> }];