HTTPS self-signed certificate authentication and data request encapsulation

Source: Internet
Author: User

At the WWDC 2016 developer conference, Apple announced a deadline: The app Transport security feature must be enabled for all apps in the App Store by January 1, 2017. APP Transport Security (ATS) is a privacy protection feature introduced by Apple in iOS 9, which blocks plaintext HTTP resources from loading, and connections must be more secure HTTPS. Apple currently allows developers to temporarily shut down ATS and continue to use HTTP connections, but the use of ATS must be mandatory for all official stores by the end of the year.

The framework used in the project is Afnetworking 3.0 and later, because of ATS, iOS only allows links beginning with HTTPS, and Apple allows to bypass ATS until December 30, 2016, as shown in:

However, applications that use HTTP to load resources will no longer be accepted from January 1, 2017, so this article explains how to use AFN to authenticate self-signed certificates (note: There is no need for certification for certificates that use CA agency certification. Directly using the link at the beginning of HTTPS for data access and loading pages) The project has been uploaded to GitHub (please click on the link if you need to refer to the source code):

Https://github.com/AustinKuture/HttpsSignatureCertificate

1, create a root class named Aknetpackegeafn here

1>. h file, creating the required get and Post methods

#import <Foundation/Foundation.h>typedef enum{              AKNetWorkGET ,   /**< GET请求 */         AKNetWorkPOST = 1 /**< POST请求 */}AKNetWorkType;typedef void (^HttpSuccess)(id json);typedef void (^HttpErro)(NSError* error);@interface AKNetPackegeAFN : NSObject+(instancetype)shareHttpManager;/*  *   netWorkType:请求方式 GET 或 POST   signature:是否使用签名证书,是的话直接写入证书名字,否的话填nil   api:请求的URL接口   parameters:请求参数   sucess:请求成功时的返回值   fail:请求失败时的返回值   *   */- (void)netWorkType:(AKNetWorkType)netWorkType Signature:(NSString *)signature API:(NSString *)api Parameters:(NSDictionary *)parameters Success:(HttpSuccess)sucess Fail:(HttpErro)fail;
@end

2>. m files, importing header files AFNetworking.h new manager properties and implementing Sharehttpmanager class methods

#import "AKNetPackegeAFN.h"#import "AFNetworking.h"@interface AKNetPackegeAFN()@property (nonatomic,strong) AFHTTPSessionManager *manager;@end@implementation AKNetPackegeAFN+(instancetype)shareHttpManager{        static dispatch_once_t onece = 0;        static AKNetPackegeAFN *httpManager = nil;        dispatch_once(&onece, ^(void){                 httpManager = [[self alloc]init];         });        return httpManager; }

Implementation of 2,get and post method

When used, convert the certificate given by the background to a. cer format into the project root, bind in the method, for example, a certificate named: Kuture.crt receive the certificate, double-click to install, then open the keychain, right-click the certificate named Kuture, select the suffix. cer Then make sure that it looks like this:

---

-

Package of GET and POST implementation methods

-(void) Networktype: (aknetworktype) Networktype Signature: (NSString *) Signature API: (NSString *) API Parameters: ( Nsdictionary *) Parameters Success: (httpsuccess) sucess Fail: (Httperro) fail{           // Turn on certificate validation mode        afsecuritypolicy *securitypolicy = [Afsecuritypolicy policywithpinningmode: Afsslpinningmodecertificate];            //are you allowed to use self-signed certificates        signature = = nil? (void) (securitypolicy.allowinvalidcertificates = NO):(securitypolicy.allowinvalidcertificates = YES);            //If you need to verify the domain name        securitypolicy.validatesdomainname = NO;              _manager = [[Afhttpsessionmanager alloc]initwithbaseurl:[nsurl URLWITHSTRING:API]];        _manager.responseserializer = [Afjsonresponseserializer serializer];        _manager.securitypolicy = securitypolicy; &nBsp      _manager.responseserializer.acceptablecontenttypes = [Nsset setwithobjects:@ "Application/json", @ "Application/xml", @ "Text/xml", @ "Text/json", @ "Text/plain", @ "Text/javascript", @ "text/html", nil];            if (signature = nil) {                & nbsp        __weak typeof (self) weakself = self;                [_manager setsessiondidreceiveauthenticationchallengeblock:^ Nsurlsessionauthchallengedisposition (nsurlsession *session, Nsurlauthenticationchallenge *challenge, Nsurlcredential *__autoreleasing *_credential) {                    &NB Sp              //Get Server Trust object               & nbsp        sectrustref servertrust = [[Challenge Protectionspace] servertrust];       &NBsp                          //import self-signed certificate                        nsstring *cerpath = [[NSBundle Mainbundle] Pathforre source:@ "Your certificate name" oftype:@ "CER"];            nsdata *cerdata = [NSData Datawithcontentsoffile:cerpath];                          ,         &N Bsp;if (!cerdata) {                            &NBS P                  nslog (@ "= = cer file is nil = =");                          ,         &N Bsp            return 0;                        }                                    ns Array *cerarray = @[cerdata];                        weakself.manager.securitypolicy.pinned certificates = Cerarray;                        seccertificateref caref = Seccertifica Tecreatewithdata (NULL, (__bridge cfdataref) cerdata);            nscassert (caref! = nil, @ "Caref is nil");                          ,         &N Bsp Nsarray *caarray = @[(__bridge ID) (CAREF)];                        nscassert (caarray! = nil, @ "Caarray is Nil ");                          ,         &N bsp;//to set the read certificate to serverTrust's root certificate                        osstatus status = Sectrustse Tanchorcertificates (Servertrust, (__bridge cfarrayref) caarray);                        sectrustsetanchorcertificatesonly (serv Ertrust, NO);            nscassert (errsecsuccess = = status, @ "Sectrustsetanchorcertificates failed");                          ,         &N bsp;//Select the processing mode of challenge authentication                        nsurlsessionauthchal lengedisposition disposition = nsurlsessionauthchallengeperformdefaulthandling;                        __autoreleasing nsurlcredential *crede Ntial = nil;                             &NBsp       //nsurlauthenticationmethodservertrust Challenge authentication method                       &NBSP;IF ([Challenge.protectionSpace.authenticationMethod isequaltostring: Nsurlauthenticationmethodservertrust]) {               //based on the client-side security policy to determine whether to trust the server , non-trust does not respond to the challenge                     &nbsp          . ; if ([WeakSelf.manager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust Fordomain: Challenge.protectionSpace.host]) {                        &NB Sp                                  // Build a certificate                       &NB           Sp      credential = [Nsurlcredential credentIalForTrust:challenge.protectionSpace.serverTrust];                          ,         &NB Sp                        //Confirmation Challenge mode         & nbsp                              &NBSP;IF (credential) {                              /    & nbsp            disposition = nsurlsessionauthchallengeusecredential;                          ,         &NB Sp                         &nbsp  ;} else {    & nbsp                           &NBSP                          ,         &NB Sp    disposition = nsurlsessionauthchallengeperformdefaulthandling;                          ,         &N Bsp   &NBSP,}                               &N Bsp                      } else {          &N Bsp                          ,         &N Bsp            //Cancel challenge                     &NB Sp                  disposition = Nsurlsessionauthchallengecancelauthenticationchallenge;         &nbsp                      }             & nbsp                          } else {    &N Bsp                          ,         &NB Sp        disposition = nsurlsessionauthchallengeperformdefaulthandling;                        }           and nbsp                        return disposition;                }];         }            if (Networktype = = 0) {                         [_manager Get:api parameters:parameters Progress:^ (nsprogress * _nonnull uploadprogress) {               } success:^ (nsurlsess Iondatatask * _nonnull task, id  _nullable responseobject) {                                   if (sucess) {          &NBS P                          ,         &NB Sp  sucess (Responseobject);                        }else{        &NB Sp                          ,         &N Bsp  nslog (@ "link exception or network not present");                        }                } failure:^ (Nsurlsessiondatatask * _nullable task, NSerror * _nonnull error) {                          &NBS P          fail (error);                }];          }else if (Networktype = = 1) {                &NB Sp                [_manager post:api parameters:parameters progress:^ (nsprogress * _ Nonnull uploadprogress) {               } success:^ (Nsurlsessiondatatask * _nonn ull task, id  _nullable responseobject) {                    &NBSP ;              if (sucess) {                &NBS P                                sucess (resp Onseobject);                       }else{            &NB Sp                                 &NBSP;NSL OG (@ "link exception or network does not exist");                        }                } failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {      &N Bsp                              fail (error);                }];          }          }

2 using the method, in the need for data acquisition or delivery of the class, directly import the header file AKNetPackegeAFN.h, and implement the method, as follows:

Creating objects
In the case of a self-signed certificate, bind the certificate (the certificate is dragged directly into the project) before using the appropriate method prior to Aknetpackegeafn.
/*
*
Networktype: Request mode GET or POST
Signature: Whether to use the signing certificate, if it is written directly to the certificate name, no words to fill nil
API: Requested URL interface
Parameters: Request Parameters
Sucess: Return value when the request succeeds
Fail: The return value when the request fails
*
*/
Aknetpackegeafn *nethttps = [Aknetpackegeafn Sharehttpmanager];
[Nethttps networktype: Request type Signature: Certificate name API: Request URL Parameters: parameter success:^ (ID JSON) {
NSLog (@ "json:%@", Json);
} fail:^ (Nserror *error) {
NSLog (@ "error:%@", Error);
}];

Original address: https://my.oschina.net/Kuture/blog/804524

HTTPS self-signed certificate authentication and data request encapsulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.