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
)?
This seems to be an undocumented behavior of
NSURLCredential
: when passingnil
as a password tocredentialWithUser: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 emptyNSString
(@""
) when you don't want to use a password.So your code should look something like:
This is what I get from my nginx's logs with a
nil
password:And with an empty string (
apikey
being the username used in response to the challenge):