wkwebview SSL Auhtentication with .p12 certificate- You do not have permission to view this page or directory using this credential"

We are implementing SSL Authentication in our application where all API And Resources is on Https Server and required ssl authentication.


We are sucessfuly implemented all API and working as expected with SSL Authentication on the same server.


It is not working at all when try to load html url in WKWebview from same server.


The certifiate we are having is in form of .p12 and certificate is verified by CA.(IT is not a Self Signed Certificate)


Now whenever we try to load H
TML file from url, it only give us 403 Forbidden Access while loading HTML Page.



Following is the code snippet that we have implemented in my WkWebview Code.


public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
       
            /// called handler if request already failed previously - increase the pefromance in request ultimately.
            if challenge.previousFailureCount > 0 {
                completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
                return
            }
           
            do {
                /// validate certificates details
                let securityIdentity = try findSecurityIdentity(named: "xxxx", password: "xxxxx")
                let credential = URLCredential(identity: securityIdentity, certificates: nil, persistence: URLCredential.Persistence.permanent)
                completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, credential)
               
            } catch let error {
               
                ///cancel auth challenge
                print(error)
                completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
            }
        }
       

    /// - Throws: throws an inbuild errors
    @objc public func findSecurityIdentity(named name: String, password: String) throws -> SecIdentity {
       
        let url = Bundle.main.url(forResource: name, withExtension: "p12")
       
        if url == nil {
            throw findError(from: .certificatesNotConfigured)
        }
       
        let data = try Data(contentsOf: url!)
        var importResult: CFArray? = nil
        let err = SecPKCS12Import(
            data as NSData,
            [kSecImportExportPassphrase as String: password] as NSDictionary,
            &importResult
        )
        guard err == errSecSuccess else {
            throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil)
        }
        let identityDictionaries = importResult as! [[String:Any]]
        return identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity
    }

It always shows 403 page in wkwebview with message "You do not have permission to view this page or directory using this credential"



Can you please let us know if there is a issue with WKWebview as i have explored some community posts here or someting we are not doing right?

Replies

First things first, the code you posted seems problematic, in that you don’t specifically look for the

NSURLAuthenticationMethodClientCertificate
authentication challenge. An authentication challenge handler should always have a form like so:
let authMethod = challenge.protectionSpace.authenticationMethod
switch authMethod {
case NSURLAuthenticationMethodClientCertificate:
    … handle this type of challenge …
case ***:
    … handle some other type of challenge …
default:
    completionHandler(.performDefaultHandling, nil)
}

However, this may not fix the issue you’re seeing. Currently shipping OS releases have a bug that prevent you from being able to handle

NSURLAuthenticationMethodClientCertificate
authentication challenges in
WKWebView
.

You should try this again on the currently seeded beta release of your target platform (for example, for iOS this would be iOS 12.0b11). Last I checked the bug was fixed there.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks for you reply , in above snippet I have just provided sample code of my test project not the Whole function so it is not including same authentication challenge handler for server trust and Client certificate etc..


Thank you for the valuable information. Looking forward to test it in iOS 12.



Can you please suggest any workaround for above mentioned bug.

Can you please suggest any workaround for above mentioned bug.

The only workaround for earlier systems is to use

UIWebView
. That runs its network requests in your app’s process, so you can catch them using a custom
NSURLProtocol
subclass and handle the authentication challenges there. The CustomHTTPProtocol sample code shows the basic idea [1].

IMPORTANT If you go down this path you should write both versions of the code, one for

WKWebView
on iOS 12 and later and one for
UIWebView
on pre-iOS 12 systems.
UIWebView
is officially deprecated starting with the iOS 12 SDK, meaning it would be a bad idea to take a long-term dependency on it.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

[1] Although the specific example it shows overrides server trust evaluation, which is unnecessary on current systems because

WKWebView
handles those authentication challenges correctly.

Hi ,


With iOS 12 released in Last week We find out that we are not able to load Any url which is https.

I have tried with "https://www.google.com" and also with other https URL.

It neither show any error in console nor it loads any content.


Everything works fine if we load any url which is "http".



Can you please let us know is there something related with the above question i have asked? is there any known bug with WKWEBVIEW with https request. This is something urgent as we are in queue to go live to appstore.

With iOS 12 released in Last week We find out that we are not able to load Any url which is https.

Well that’s weird. As far as I know

WKWebView
works just fine on iOS 12 (and with regards this issue, client certificate authentication, it works better). I’ve no idea why you’re unable to load HTTPS pages.

At this point it’d be best if you opened a DTS tech support incident so that I can take a more detailed look at your code.

Oh, one last thing. It occurs me that one way you could ‘break’ all HTTPS pages is to implement an authentication challenge handler incorrectly. My recommendation is that you (temporarily) remove your authentication challenge handler to see if that fixes HTTPS.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"