Question

I have an iOS app which logs-in a user and then authenticates that user with an appKey. The didReceiveAuthenticationChallenge delegate method on NSURLConnection is sufficient for providing a username / password with an NSURLCredential. However, I'm having trouble creating an NSURLCredential with only an appKey (just one piece of auth data, not two). Is there anyway to provide authentication details to a server with NSURLConnection with only a key?

The following curl request works perfectly by only providing the appKey, no password:

curl -u <app key>: -H "Accept: application/json" https://dev.sitename.com/api/v1/webpage -v

This is how I've translated the above cURL authentication part to Objective-C:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    // Authenticate the user with AppKey based on the credentials provided
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *credential = [NSURLCredential credentialWithUser:[keychainItem objectForKey:@"APP KEY"] password:nil persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }
}

This should work, but every time I try it the authentication fails. As you can see I've set the password parameter to nil. I've also tried filling in both parameters. Nothing seems to work.

Any ideas on how I could only pass one parameter to the server using NSURLConnection? Is there any way to get error information from the didReceiveAuthenticationChallenge delegate method (I'm aware of didReceiveResponse)?

Was it helpful?

Solution

This seems to be an undocumented behavior of NSURLCredential: when passing nil as a password to credentialWithUser:password:persistence:, and using this credential to respond the authentication challenge, iOS ignore the credential altogether.

The solution is to replace the nil by an empty NSString (@"") when you don't want to use a password.

So your code should look something like:

NSURLCredential *credential = [NSURLCredential credentialWithUser:[keychainItem objectForKey:@"APP KEY"] password:@"" persistence:NSURLCredentialPersistenceForSession];

This is what I get from my nginx's logs with a nil password:

xxx.xxx.xxx.xxx - - [18/Aug/2013:23:21:14 +0200] "GET /tmp HTTP/1.1" 401 188 "-" "test/1.0 CFNetwork/609.1.4 Darwin/12.4.0"

And with an empty string (apikey being the username used in response to the challenge):

xxx.xxx.xxx.xxx - apikey [18/Aug/2013:23:21:16 +0200] "GET /tmp HTTP/1.1" 200 136 "-" "test/1.0 CFNetwork/609.1.4 Darwin/12.4.0"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top