I am in the process of replacing UIWebView
in our app with WKWebView
and I have run into a cookie problem. There is a login process in our app where a webform is shown in a web view, and if the login was successful we call a service that gives us our auth token. The service recognises a successful login by a session cookie that was set in the web view. With UIWebView
we didn't need to do anything to pass this cookie to the token request since both UIWebView
and NSURLSession
use the shared NSHTTPCookieStorage
. WKWebView
however doesn't use the shared cooke storage, so I copy all cookies from it to the shared storage before calling the token service:
[webView.configuration.websiteDataStore.httpCookieStore getAllCookies:^(NSArray* cookies) {
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}];
This seem to work if I print out the cookies in the shared storage
for (NSHTTPCookie *cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies) {
NSLog(@"name: %@\tvalue: %@", cookie.name, cookie.value);
}
I get this:
name: mobile value: 220|220
name: BDJSESSIONID value: 0000YHfKy0d8aGHsOKPZBFznsQt:bdaix570
name: vp value: ourdomain-com
name: ukontrol value: nb8sfm1:1590215000215:
name: ACENBP value: ffffffffc3a01a5945525d5f4f58455e445a4a423660
name: clientsession value: NaN
name: _ga value: GA1.2.2108673536.1590134296
name: _gid value: GA1.2.570415333.1590134296
name: xLocale value: da:DK
name: _gat_UA-56861410-1 value: 1
name: PD_STATEFUL_c57e342c-fccf-4a0c-bb38-de5e09832f2c value: %2Fcardapp.services
name: PD_STATEFUL_00819ac9-1bb8-4375-80ff-00c0285bab51 value: %2Fcardapp.services
This looks exactly the same as when I use a UIWebView
.
The BDJSESSIONID
cookie is the important one here. If I am missing that, the call to the token service will create a new session, where the user is not logged in.
My problem now is that some of the cookies (including BDJSESSIONID
) are missing when I call the token service like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
NSURLSessionTask *sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
...
}];
[sessionTask resume];
These are the cookies actually sent:
I should note that the code for calling the token service was not changed from when we were using UIWebView
.