web-dev-qa-db-ja.com

SwiftでのWKWebViewによる認証

私のiOSアプリでは、WKWebViewを使用して、アプリケーションの外部URLをラップします。このURLには基本認証が必要です(次のスクリーンショットのように、ユーザーとパスワードの資格情報が必要です)。

enter image description here

いくつかの調査の後、自動ログインを有効にするためにdidReceiveAuthenticationChallengeメソッドを使用しようとしているので、それがどのように機能するのか理解できません。

これは私のコードです。

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)
        }
    }
}

私はこの例外に直面しています:

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

didReceiveAuthenticationChallengeメソッドを削除すると、URLに到達できますが、明らかに間違った資格情報が表示されます。

誰かが私が間違っていることを説明してもらえますか?

15
Giovanni Grano

次の行を追加します。

completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)

didReceiveAuthenticationChallengeの最後に問題を解決しました。

17
Giovanni Grano

私はパーティーに遅れますが、それでも誰かにとっては役に立ちます。

WKWebviewで認証チャレンジをサポートするにはSwift 4、以下のようにコードを完成させます

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