When I create new request for WKWebView
with authentication cookie and send the request, WKWebView
correctly loads protected web page:
let req = NSMutableURLRequest(URL: NSURL(string: urlPath)!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies([myAuthCookie]);
req.allHTTPHeaderFields = headers;
webView.loadRequest(req)
The problem is, that when user clicks on a any link in the web page, with new request WKWebView
loses authentication cookie and is redirected to logon page. Cookie domain and path are filled and correct.
I am aware of the missing functionality of WKWebView
mentioned here.
Thanks in advance for any idea.
The best thing to do is to store your cookie into the
[NSHTTPCookieStorage sharedHTTPCookieStorage]
Then each time you want to load the request, call this function instead:
- (void)loadRequest:(NSURLRequest *)request {
if (request.URL) {
NSDictionary *cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
if ([cookies objectForKey:@"Cookie"]) {
NSMutableURLRequest *mutableRequest = request.mutableCopy;
[mutableRequest addValue:cookies[@"Cookie"] forHTTPHeaderField:@"Cookie"];
request = mutableRequest;
}
}
[_wkWebView loadRequest:request];
}
It extract the right cookies from shared cookies and includes it into your request