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:
[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.
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
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) ?? []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With