如何使用WKWebView进行用户身份验证? [英] How to use WKWebView for user authentication?

查看:140
本文介绍了如何使用WKWebView进行用户身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:检索accessToken和用户详细信息,而无需使用任何本机控件输入用户凭据.使用SSO登录相同.

Goal: Retrieve accessToken and user details without using any of the native controls to enter user credentials. Use SSO login for same.

步骤:iOS应用和用户执行

Steps: iOS App and user perform

1.用户选择SSO登录选项

1.User chooses SSO Login option

2.用户重定向到SSO登录URL

2.User redirects to SSO Login URL

3.SSO登录URL显示一个JavaScript警报,用于输入用户名和 密码.(在台式机和移动浏览器上,它不会显示任何内容 在网络视图中)

3.SSO Login URL shows an JavaScript Alert to input username and password.(On desktop and mobile browsers, it doesn't show anything in webview)

4.一旦用户输入凭据,他将被重定向到我们的服务器,该服务器将返回包含用户数据的html页面.

4.Once the user enters the credentials, he is redirected to our server, which returns html page with user data.

我尝试过的事情: 尝试使用以下

func viewDidLoad(){
        let pref = WKPreferences()
        pref.javaScriptEnabled = true
        pref.javaScriptCanOpenWindowsAutomatically = true

        /* Create a config using pref*/
        let configuration = WKWebViewConfiguration()
        configuration.preferences = pref

        /* Instantiate the web view */

        let webviewFrame = CGRect(x:0,y: txtSSOLoginUrl.bounds.maxY, width: self.view.bounds.width, height: self.view.bounds.height - 40)
        webView = WKWebView(frame:webviewFrame,configuration: configuration)
        view.addSubview(webView)
        webView.navigationDelegate = self
        webView.uiDelegate  = self
        webView.load(request as URLRequest)
}

extension SSOLoginViewController:WKUIDelegate,WKNavigationDelegate{
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        print("DID START NAV didStartProvisionalNavigation")

    }
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        print("RECEIVERD SERVER REDIRECT")

    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("EERRORRR : \(error)")
    }


    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print ("ERRRRRR : \(error)")
    }

    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        print("runJavaScriptAlertPanelWithMessage")
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)

        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
            completionHandler()
        }))

        self.present(alertController, animated: true, completion: nil)
        alertController.popoverPresentationController?.sourceView = self.view
    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        print("runJavaScriptConfirmPanelWithMessages")
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)

        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
            completionHandler(true)
        }))

        alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
            completionHandler(false)
        }))

        self.present(alertController, animated: true, completion: nil)

        alertController.popoverPresentationController?.sourceView = self.view
    }

    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        print("runJavaScriptTextInputPanelWithPrompt")
        let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .actionSheet)

        alertController.addTextField { (textField) in
            textField.text = defaultText
        }
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
            if let text = alertController.textFields?.first?.text {
                completionHandler(text)
            } else {
                completionHandler(defaultText)
            }

        }))
        alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in

            completionHandler(nil)

        }))

        self.present(alertController, animated: true, completion: nil)
        alertController.popoverPresentationController?.sourceView = self.view
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        print("DID FINISH NAV didFinish navigation")

    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        print("DECIDE POLICY WKNavigationResponse \(navigationResponse)")
        decisionHandler(.allow)

    }

    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        print("DID RECEIVE URLAuthenticationChallenge")
         //var cred = URLCredential(user: "username", password: "Password123!", persistence: URLCredential.Persistence.none)
         //challenge.sender?.use(password, for: challenge)
        completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)

    }
 }

输出 没有看到询问用户凭据的警报.

Output Not seeing alert asking user credentials.

预期产量 收到带有用户名和密码文本字段的警报,以输入凭据.

Expected Output Get an alert with username and password textfields to input credentials.

推荐答案

我们为解决此问题所做的是,我们使用了服务器提供的HTML页面,后端在请求中提供了所需的详细信息,从而进行了实际的重定向.隐藏的领域.该重定向URL被提供给了使用他们自己的SSO登录名的另一方,但是通过我们的应用程序在Web视图中提供了该URL.这不是解决问题的方法,而是一种解决方法.从来没有真正解决过这个问题.

What we did to get around this problem was, we used an HTML page which was served by the server and the backend did the actual redirection with required details in the hidden field. That redirect URL was given to the other party which used their own SSO login, but through our app, inside a web view. This is not a solution to the problem but a workaround. Never actually got to solve this issue.

这篇关于如何使用WKWebView进行用户身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆