How to use NSURLConnection to connect with SSL for an untrusted cert?

后端 未结 13 1814
盖世英雄少女心
盖世英雄少女心 2020-11-22 01:29

I have the following simple code to connect to a SSL webpage

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection send         


        
13条回答
  •  日久生厌
    2020-11-22 01:53

    I can't take any credit for this, but this one I found worked really well for my needs. shouldAllowSelfSignedCert is my BOOL variable. Just add to your NSURLConnection delegate and you should be rockin for a quick bypass on a per connection basis.

    - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space {
         if([[space authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) {
              if(shouldAllowSelfSignedCert) {
                   return YES; // Self-signed cert will be accepted
              } else {
                   return NO;  // Self-signed cert will be rejected
              }
              // Note: it doesn't seem to matter what you return for a proper SSL cert
              //       only self-signed certs
         }
         // If no other authentication is required, return NO for everything else
         // Otherwise maybe YES for NSURLAuthenticationMethodDefault and etc.
         return NO;
    }
    

提交回复
热议问题