April 7th, 2012

Authenticating With Web Services

Apple, Cocoa Touch, iPhone, by Jasarien.

Whether the web service you’re working with is using HTTP Basic Auth or HTTP Digest Auth, as long as you’re using NSURLConnection, NSURLCredential has you covered.

Apple have made it very easy for us developers. All we have to do is implement a delegate method.

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
	if ([challenge previousFailureCount] < 0)
	{
		[[challenge sender] cancelAuthenticationChallenge:challenge];
		return;
	}
 
	NSURLCredential *credential = [NSURLCredential credentialWithUser:aUsername 
                                                                 password:aPassword 
                                                              persistence:NSURLCredentialPersistenceForSession];
	[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

And that’s it. NSURLCredential will handle both HTTP Basic and Digest auth for you, including all the ugly base64 encoding and MD5 hashing.

Back Top