10
votes

I'm building an app that uses Single Sign On for users to log in. After the user enters a successful ID and password, the web side of things returns headers which I grab and store in my app. The WKWebView also sets a cookie that the user successfully logged in. This is what I want to avoid or undo.

The undesired behavior that I'm seeing is that if I log in a user, everything goes well, and then I log them out and go to log back in again, the WKWebView thinks the user is still logged in and takes them to an undesired URL.

In iOS 9, mitigating this is fairly simple:

let config = WKWebViewConfiguration()
config.websiteDataStore = WKWebsiteDataStore.nonPersistentDataStore()

let webView = WKWebView(frame: .zero, configuration: config)

However in iOS 8.4, making making sure the cookies are clear each time the user goes in to load the Single Sign On URL is more complicated.

I've tried approaches where I loop through cookies in NSHTTPCookieStorage.sharedHTTPCookieStorage() and remove them. Unfortunately, the cookie count is 0.

I've also tried removing the /Cookies directory in NSFileManager.defaultManager(). This also does not work.

One thing that kind of worked was doing the following. Although this approach didn't allow me to get the headers because a redirect after login needed to happen and this interfered (in iOS 9+ and 8.4)

req = NSMutableURLRequest(URL: url)
req?.HTTPShouldHandleCookies = false
let webView = WKWebView()
webView.loadRequest(req ?? NSURLRequest(URL: url))

I'd prefer to clear cookies in the deinit of my view that holds my WKWebView if that's a possible solution here.

2
Please check my answer for similar question below: stackoverflow.com/questions/38480867/…Roman Ermolov

2 Answers

0
votes

This might be a longshot, but what about overriding the cookie accept policy to reject all cookies at the time of sign in?

NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = .Never

Another idea would be to manually mange the cookies with a custom WKProcessPool subclass (which is not really documented). I believe that's how Firefox manages any cookie issues.

0
votes

Even if you mention it, is this the approach you've already tried in your deinit?

let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        for cookie in storage.cookies! {
            storage.deleteCookie(cookie)
        }