IOS Development Support https Request and ssl Certificate Configuration Detailed Explanation

  • 2021-10-16 05:07:47
  • OfStack

IOS Development Support https Request and ssl Certificate Configuration Detailed Explanation

Foreword:

As we all know, Apple has said that starting from 2017, it will block the resources of http and push https

The landlord just recently changed http to https, and shared 12 with friends who haven't started yet

1. Certificate preparation

1. Certificate conversion

After the server personnel send you the crt certificate, go to the certificate path and execute the following statement

//openssl x509-in Your Certificate.crt-out Your Certificate.cer-outform der

In this way, you can get cer type certificate. Double-click to import the computer.

2. Put the certificate into the project

1. You can directly drag the converted cer file into the project.

2. You can find the certificate you imported in the keychain, right-click and export the project, and you can export the certificate of the. cer file

2. Code preparation


<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

1.1 NSURLConnection settings support https.

In the update of iOS9 in 2015, NSURLConnection was abandoned and replaced by NSURLSession, so it is not recommended that you continue to use this class for network requests (there are also AFNetWorking 2.x versions). However, considering some old programs, you can't change them when you say they are changed, and replace them when you say they are replaced, so you still need to popularize them. What do you need to do if you use NSURLConnection?

The code is as follows:


- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{

  if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
    //  Tell the server that the client trusts the certificate 
    //  Creating Credentials Object 
    NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    //  Tell the server to trust the certificate 
    [challenge.sender useCredential:credntial forAuthenticationChallenge:challenge];
  }
}

You simply need to add the proxy method above, and you can add support for https requests without affecting your original request.

1.2 The NSURLSession settings support https.

Now it is recommended to use NSURLSession to handle related network requests. If you use the class that comes with the system, you can refer to the following code:


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {

  //  Determine whether you trust the server certificate 
  if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
    //  Tell the server that the client trusts the certificate 
    //  Creating Credentials Object 
    NSURLCredential *credntial = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    //  Pass completionHandler Tell the server to trust the certificate 
    completionHandler(NSURLSessionAuthChallengeUseCredential,credntial);
  }
  NSLog(@"protectionSpace = %@",challenge.protectionSpace);
}

2. Send network request articles using AFNetWorking

AFNetworking is a delightful network library for iOS and Mac, OS, X. It is built on top of NSURLConnection, NSOperation, and other familiar Foundation technologies. Its good architecture, rich api, and modular construction make it easy to use.

2.1 AFNetWorking 2. x version

With this release in mind, we can also use the AFHTTPRequestOperationManager class to handle network requests. So what we have to do is to give this class a few parameters so that it can support https requests. The code is as follows:

Support https (check certificate, can't grab package):


// 1. Initialize a singleton class 
  AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
  mgr.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate;
  // 2. Setting Certificate Mode 
  NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];
  NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
  mgr.securityPolicy.pinnedCertificates = [[NSArray alloc] initWithObjects:cerData, nil];
  //  Whether the client trusts the illegal certificate 
  mgr.securityPolicy.allowInvalidCertificates = YES;
  //  Whether to verify the domain name in the Certificate Domain field 
  [mgr.securityPolicy setValidatesDomainName:NO];

Support https (do not verify the certificate, you can grab the package to view):


 // 1. Initialize a singleton class 
  AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
  mgr.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate;
  // 2. Setting Non-Verification Certificate Mode 
  mgr.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  mgr.securityPolicy.allowInvalidCertificates = YES;
  [mgr.securityPolicy setValidatesDomainName:NO];

2.2 AFNetWorking 3. x version

After Xcode7.0, Apple abandoned the NSURLConnection method, and used NSURLSession for data requests. AFN, which is the most used third-party library of network request class, was also updated in time-AFN version 3.0. In the new version, AFHTTPRequestOperationManager based on NSURLConnection encapsulation is discarded, and AFHTTPSessionManager based on NSURLSession encapsulation is used instead.

Support https (verify certificate, do not grab packets):


// 1. Initialization 
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  manager.securityPolicy.SSLPinningMode = AFSSLPinningModeCertificate;
  // 2. Setting Certificate Mode 
  NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];
  NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
  manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];
  //  Whether the client trusts the illegal certificate 
  mgr.securityPolicy.allowInvalidCertificates = YES;
  //  Whether to verify the domain name in the Certificate Domain field 
  [mgr.securityPolicy setValidatesDomainName:NO];

Support https (do not verify the certificate, you can grab the package to view):


// 1. Initialization 
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  // 2. Setting Non-Verification Certificate Mode 
  manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  manager.securityPolicy.allowInvalidCertificates = YES;
  [manager.securityPolicy setValidatesDomainName:NO];

The configuration is completed here, and I hope it will be helpful to you.


Related articles: