Search code examples
iphoneobjective-ccocoa-touchnsurlconnectionhttp-caching

Issue with NSURLConnection, Basic Auth and Cookies


I have discovered that the server I make REST calls to passes on cookies to my iPhone. It also employs HTTP Basic Auth.

I have an app where you can change accounts used for the authentication, however I have discovered that changing the credentials doesn't matter since didReceiveAuthenticationChallenge is never called.

I have looked into two potential fixes:

  • removing the cookies manually whenever credentials are changed
  • setting [request setHTTPShouldHandleCookies:NO]

I wonder if I'm understanding this correctly. I expected that NSURLRequestReloadIgnoringCacheData would take care of caching, but it doesn't seem to be the case.

How can I resolve this?

EDIT: I've just tried setting shouldHandleCookies to NO, but it seems that the cookies are still passed on to the server.


Solution

  • Rob, you are quite right, there does seem to be a problem with this. Cookies are set in some cases that keep the old auth credentials persisted. Others have suggested you may need to clear the cookies like so, and this solved the problem for me:

     - (void)clearCookiesForURL {
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray *cookies = [cookieStorage cookiesForURL:_URL];
        for (NSHTTPCookie *cookie in cookies) {
            NSLog(@"Deleting cookie for domain: %@", [cookie domain]);
            [cookieStorage deleteCookie:cookie];
        }
      }
    

    Take a look at this question for more didReceiveAuthenticationChallenge getting called only once iPhone