Problem with NSURLConnection, Basic Auth and Cookies

I found that the server I am making REST calls to sends cookies to my iPhone. It also uses HTTP Basic Auth.

I have an application in which you can change the accounts used for authentication, however, I found that changing the credentials does not matter, since didReceiveAuthenticationChallenge never called.

I examined two possible fixes:

  • manually deleting cookies when changing credentials.
  • [request setHTTPShouldHandleCookies:NO]

I wonder if I understand this correctly. I expected NSURLRequestReloadIgnoringCacheData take care of caching, but it doesn't seem to be that way.

How can i solve this?

EDIT: I just tried setting shouldHandleCookies to NO , but it seems cookies are still being sent to the server.

+4
source share
2 answers

Rob, you're absolutely right, there seems to be a problem with that. In some cases, cookies are set to preserve old credentials. Others suggested that you might need to clear cookies like this, 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 again didReceiveAuthenticationChallenge receives a call only once iPhone

+7
source

Safe speed:

 func clearCookies(forURL URL: NSURL) -> Void { let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() let cookies = cookieStorage.cookiesForURL(URL) ?? [] for cookie in cookies { print("Deleting cookie for domain: \(cookie.domain)") cookieStorage.deleteCookie(cookie) } } 

If you want to get a String , you can always flatMap initializer:

 let cookies = NSURL(string: string).flatMap(cookieStorage.cookiesForURL) ?? [] 
+2
source

All Articles