Authentication with Wkwebview in Swift

Authentication with WKWebView in Swift

Add the following line:

completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)

at the end of didReceiveAuthenticationChallenge solved the problem.

swift 3 - http authentication in WKWebView

Fixed variant #1 by adding "_":

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

let user = "user"
let password = "pass"
let credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
challenge.sender?.use(credential, for: challenge)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential)
}

Swift 4 WKWebView Authentication From Keychain

Using a token based authentication as suggested, tokens are generated and passed back in the response header upon user login.

WKNavigationDelegate has a method that pass in the WKNavigationResponse object, which allows you to view the response, including the headers.

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
... do stuff

let headerValue = (navigationResponse.response as! HTTPURLResponse).allHeaderFields["X-HEADER-NAME"] as? String

... do more stuff
}

The UserDefaults class can be used to store, retrieve, or delete the token.

let tokenKey = "unique.identifier"
let newToken = "NEWTOKEN12345"
let oldToken = UserDefaults.standard.string(forKey: tokenKey)

if (oldToken != nil) {
UserDefaults.standard.removeObject(forKey: tokenKey)
}

UserDefaults.standard.set(token, forKey: tokenKey)

To add a header to your initial request only, you can modify the URLRequest object to add a header before the webView loads it.

override func viewDidLoad() {
... do stuff

let tokenKey = "unique.identifier"
let token = UserDefaults.standard.string(forKey: tokenKey)

var request = URLRequest(url:URL(string: "https://www.example.com/users/login")!)

if (token != nil) {
request.addValue(token!, forHTTPHeaderField: header)
}

... do more stuff

webView.load(request)
}


Related Topics



Leave a reply



Submit