简体   繁体   中英

AuthenticationMethodServerTrust is nil in iOS 9

I have been trying to implement a way to do public key pinning in my iOS 8+ app using NSURLSession.

What I do is just implement the delegate method didReceiveChallenge and get the challenge.protectionSpace.authenticationMethod and check if it is equal to NSURLAuthenticationMethodServerTrust.

If it is equal to NSURLAuthenticationMethodServerTrust i check the certificate and compare it with my local copy.

This works fine on iOS 8 but on iOS 9 I don't receive an authentication method equal to NSURLAuthenticationMethodServerTrust. I receive NSURLAuthenticationMethodClientCertificate so I can not access the challenge.protectionSpace.serverTrust property.

Any ideas?

public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)
{


      if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
        {
            // Verify the identity of the server
                    println("Trusted")
                    return challenge.sender.performDefaultHandlingForAuthenticationChallenge!(challenge)

        }
        println("Not trusted")
        return challenge.sender.cancelAuthenticationChallenge(challenge)
    }
}

Your callback can be called multiple times for different protection spaces. What's happening here is that the order of those calls has changed, and the server trust protection space call is apparently not happening first for some reason in iOS 9.

The problem is that you are canceling the first challenge, which effectively terminates the connection. Don't do that. Instead, use "perform default handling".

You also presumably don't want to perform default handling for the server trust case, because that's equivalent to not writing the custom handler at all. Instead, check the key, and perform the default handling only if it is the key you want, else cancel the authentication challenge.

Or maybe I'm misreading your code. It looks like there is some code missing. It may be that you aren't handling the non-server-trust case at all, in which case that's the problem. If you don't call something for every challenge, the connection will simply sit there forever, waiting for you to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM