web-dev-qa-db-fra.com

Authentification avec WKWebView dans Swift

Dans mon application iOS, j'aimerais utiliser un WKWebView pour encapsuler une URL externe dans l'application. Cette URL nécessite une authentification de base (elle nécessite des informations d'identification d'utilisateur et de mot de passe, comme dans la capture d'écran suivante).

enter image description here

Après quelques recherches, j'essaie d'utiliser la méthode didReceiveAuthenticationChallenge, afin d'activer une connexion automatique, donc je ne comprends pas comment cela fonctionne.

Ceci est mon code.

import UIKit
import WebKit

class WebViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView?

    private var request : NSURLRequest {
        let baseUrl = "https://unimol.esse3.cineca.it/auth/Logon.do"
        let URL = NSURL(string: baseUrl)!
        return NSURLRequest(URL: URL)
    }

    /* Start the network activity indicator when the web view is loading */
    func webView(webView: WKWebView,
                 didStartProvisionalNavigation navigation: WKNavigation){
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }

    /* Stop the network activity indicator when the loading finishes */
    func webView(webView: WKWebView,
                 didFinishNavigation navigation: WKNavigation){
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }

    func webView(webView: WKWebView,
                 decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,
                                                   decisionHandler: ((WKNavigationResponsePolicy) -> Void)){
        decisionHandler(.Allow)
    }

    func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

        if challenge.protectionSpace.Host == "https://unimol.esse3.cineca.it/auth/Logon.do" {
            let user = "*******"
            let password = "******"
            let credential = NSURLCredential(user: user, password: password, persistence: NSURLCredentialPersistence.ForSession)
            challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
        }
    }

    override func viewDidLoad() {
        /* Create our preferences on how the web page should be loaded */
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = false

        /* Create a configuration for our preferences */
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences

        /* Now instantiate the web view */
        webView = WKWebView(frame: view.bounds, configuration: configuration)

        if let theWebView = webView {
            /* Load a web page into our web view */
            let urlRequest = self.request
            theWebView.loadRequest(urlRequest)
            theWebView.navigationDelegate = self
            view.addSubview(theWebView)
        }
    }
}

Je fais face à cette exception:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[MyUnimol.WebViewController webView:didReceiveAuthenticationChallenge:completionHandler:] was not called'

Si je supprime la méthode didReceiveAuthenticationChallenge, je suis en mesure d'accéder à l'URL mais cela me donne, de manière inconsciente, des informations d'identification erronées.

N'importe qui pourrait m'expliquer ce que je fais mal s'il vous plait?

15
Giovanni Grano

Ajoutez la ligne suivante:

completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)

à la fin de didReceiveAuthenticationChallenge a résolu le problème.

17
Giovanni Grano

je suis en retard pour faire la fête mais cela peut quand même être utile à quelqu'un.

Pour prendre en charge le défi d'authentification dans WKWebview Swift 4, code complet comme ci-dessous

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        guard let hostname = webView.url?.Host else {
            return
        }

        let authenticationMethod = challenge.protectionSpace.authenticationMethod
        if authenticationMethod == NSURLAuthenticationMethodDefault || authenticationMethod == NSURLAuthenticationMethodHTTPBasic || authenticationMethod == NSURLAuthenticationMethodHTTPDigest {
            let av = UIAlertController(title: webView.title, message: String(format: "AUTH_CHALLENGE_REQUIRE_PASSWORD".localized, hostname), preferredStyle: .alert)
            av.addTextField(configurationHandler: { (textField) in
                textField.placeholder = "USER_ID".localized
            })
            av.addTextField(configurationHandler: { (textField) in
                textField.placeholder = "PASSWORD".localized
                textField.isSecureTextEntry = true
            })

            av.addAction(UIAlertAction(title: "BUTTON_OK".localized, style: .default, handler: { (action) in
                guard let userId = av.textFields?.first?.text else{
                    return
                }
                guard let password = av.textFields?.last?.text else {
                    return
                }
                let credential = URLCredential(user: userId, password: password, persistence: .none)
                completionHandler(.useCredential,credential)
            }))
            av.addAction(UIAlertAction(title: "BUTTON_CANCEL".localized, style: .cancel, handler: { _ in
                completionHandler(.cancelAuthenticationChallenge, nil);
            }))
            self.parentViewController?.present(av, animated: true, completion: nil)
        }else if authenticationMethod == NSURLAuthenticationMethodServerTrust{
            // needs this handling on iOS 9
            completionHandler(.performDefaultHandling, nil);
        }else{
            completionHandler(.cancelAuthenticationChallenge, nil);
        }
    }
4
shesh nath