swift/objetive c ssl certificates

Discussion in 'iOS Programming' started by sgs1, Dec 18, 2014.

  1. sgs1 macrumors newbie

    Joined:
    Jul 14, 2014
    #1
  2. Sean7512 macrumors 6502a

    Joined:
    Jun 8, 2005
    #2
    So your site has a self-signed ssl certificate and you want to visit it in a web view? I have done this using a UIWebView (I am assuming it works for WKWebView too).

    Before you attempt to load your page in the view, you need to make a call via NSURLConnection and explicitly trust the self-signed ssl cert. You will get notified via NSURLConnectionDelegate when a secure connection is being made with an invalid cert, where you can optionally trust it in your code or not.


    Obj-C:
    Code:
    - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && [challenge.protectionSpace.host isEqualToString:@"myDomain.com") {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
        } else {
            [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
        }
    }
    
    Swift:
    Code:
    func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && challenge.protectionSpace.host == "myDomain.com" {
            let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
            challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
        } else {
            challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)
        }
    }
    

    The code above will accept the connection if the host matches what I expect it to or else if will do the default handling. This way your app won't accept all invalid certs, just the one from your host. Note that this isn't the best option, you probably want to do further verification to ensure you are connection to the right host :)

    This method works out really well for our app, as we have to hit a REST login endpoint to login in the user before we attempt to show the webpage, and that initial login call causes our ssl cert trust to get activated and then the web view can access our site without issue.

    Hopefully that helps!
     
  3. sgs1 thread starter macrumors newbie

    Joined:
    Jul 14, 2014
    #3
    Hi, thanks for the reply and sorry for the delay.
    I've tried that code and it doesn't work. I paste here the entire code with the error:

    Code:
    //
    //  ViewController.swift
    //  inviojs
    //
    //  Created by sags on 26/11/14.
    //  Copyright (c) 2014 All rights reserved.
    //
    
    import UIKit
    import WebKit
    
    class ViewController: UIViewController, WKScriptMessageHandler {
        
        @IBOutlet var containerView : UIView! = nil
        var webView: WKWebView?
        
        override func loadView() {
            super.loadView()
            
            
            var contentController = WKUserContentController();
           
            contentController.addScriptMessageHandler(
                self,
                name: "callbackHandler"
            )
            
            var config = WKWebViewConfiguration()
            config.userContentController = contentController
            
            self.webView = WKWebView(
                frame: self.containerView.bounds,
                configuration: config
            )
            self.view = self.webView!
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
    
            
            var urlPath = "https://an.url"
            var url: NSURL = NSURL(string: urlPath)!
            var request: NSURLRequest = NSURLRequest(URL: url)
            var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
            connection.start()
            self.webView!.loadRequest(request)
            
            
        }
    
        
        func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
            if(message.name == "callbackHandler") {
                println("JavaScript is sending a message \(message.body)")
            }
            if (message.body as NSString == "ready")
            {
                println("ha inviato un ok")
                webView?.evaluateJavaScript("hello(3,'ciao')",
                    
                    completionHandler: {(value, error) in println("got value: \(value) error:\(error)")})
                webView?.evaluateJavaScript("obj.hello(3,'ciao')",
                    
                    completionHandler: {(value, error) in println("got value: \(value) error:\(error)")})
                
             
            
            }
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
        func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && challenge.protectionSpace.host == "somedomain.net" {
                let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
                challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
            } else {
                challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)
            }
        }
        
    
    
    }
    
    
    The error is this:
    NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
     
  4. kaiba macrumors newbie

    Joined:
    Jun 9, 2015
    #4
    The code above works fine in iOS 8 but don't work in iOS 7. Is there any solution for iOS 7 ?

    Error (iOS 7):
    NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)


    thanks !!!
     

Share This Page