Losing cookies in WKWebView

15.8k views Asked by At

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.

3

There are 3 answers

5
The Windwaker On

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

0
Sebastien Martin On

You can inject some javascript into the we view to load the cookies so that requests initiated by the web view will also have your cookies. See the answer to this question for more details:

https://stackoverflow.com/a/26577303/251687

3
Alex On

I suppose when you set it in the request you are sending the cookie to the server but NOT setting it in the WKWebview. The cookies are usually set by the server in the "Set-Cookie" header and then it should be persisted. So if if you don't have an issue with cookie passing all the way to the server and back you can do a trick:

  1. send the cookie in the first request
  2. make the server send it back in the "Set-Cookie" header
  3. every subsequent request should have the cookie

I haven't tried the approach yet but will be very surprised if it doesn't work.

The alternative as mentioned by Sebastien could be do inject it via javascript. Be mindful though that you cannot set "HTTP-Only" flag this way and the cookie will be available by all the scripts running (https://www.owasp.org/index.php/HttpOnly).

I'm still trying to find a natural way to set the cookie but I don't think it exists.

Hope it helps.