Search code examples
iosnsurlconnectionhttp-authenticationnsurlconnectiondelegatensurlcredential

NSURLConnection doesn't call NSURLConnectionDelegate authentication methods after an HTTP 401


I'm consume a web service that uses HTTP basic auth with an NSURLConnection. In my NSURLConnectionDelegate, I implemented –[NSURLConnectionDelegate connection:canAuthenticateAgainstProtectionSpace:], –[NSURLConnectionDelegate connection:didCancelAuthenticationChallenge:], and –[NSURLConnectionDelegate connection:didReceiveAuthenticationChallenge:], but none of them get called.

I've tried implementing –[NSURLConnectionDelegate connectionShouldUseCredentialStorage:] to return both YES and NO, but that had no effect.

I also ensured that my NSURLCredentialStorage was empty.

Finally, instead of implementing –[NSURLConnectionDelegate connection:canAuthenticateAgainstProtectionSpace:], –[NSURLConnectionDelegate connection:didCancelAuthenticationChallenge:], and –[NSURLConnectionDelegate connection:didReceiveAuthenticationChallenge:], I implemented –[NSURLConnectionDelegate connection:willSendRequestForAuthenticationChallenge:], but it wasn't called either.

What can I do to make NSURLConnection call NSURLConnectionDelegate's authentication callbacks?


Solution

  • My HTTP server isn't returning a WWW-Authenticate header.

    My server's response:

    HTTP/1.1 401 Unauthorized
    Date: Wed, 19 Jun 2013 14:43:30 GMT
    Server: Apache-Coyote/1.1
    Expires: Wed, 19 Jun 2013 14:43:30 GMT
    Vary: Accept-Encoding,User-Agent
    Cache-Control: no-store, no-cache, must-revalidate, private, max-age=0
    Content-Length: 0
    Content-Type: text/plain
    

    Another server response with a WWW-Authenticate header:

    HTTP/1.1 401 Authorization Required
    Date: Wed, 19 Jun 2013 14:44:47 GMT
    Server: Apache/2.2.17 (CentOS)
    WWW-Authenticate: Basic realm="[LDAP/PROD] Active Directory"
    Content-Length: 0
    Connection: close
    Content-Type: text/plain
    

    It looks like NSURLConnection requires the WWW-Authenticate header in its response for it to call NSURLConnectionDelegate's authentication callbacks.

    I've filed a radar about this. Please duplicate it.

    Apparently, I'll have to manually set the Authorization header since NSURLConnection will not allow you to proactively authenticate with NSURLCredential.