Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 701
Mathias Avatar asked Jan 19 '23 16:01

Mathias


2 Answers

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

like image 199
oknox Avatar answered Jan 29 '23 07:01

oknox


Safe Swift:

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 receive a String you can always flatMap the failable NSURL initializer:

let cookies = NSURL(string: string).flatMap(cookieStorage.cookiesForURL) ?? []
like image 36
fpg1503 Avatar answered Jan 29 '23 07:01

fpg1503