Christian Beer

Christian Beer

NSURLRequest and Authentication

The internet is not only browsers and static HTML pages anymore. Most apps today also talk to servers and get or send their precious data. To prevent unwanted guests to steal your data you must think about authentication.

There is an easy way to add authentication information to a request: http://user:very!secure$password!!

But that’s not cool. You need to add these information to all requests and that can be quite a hassle.

We are lucky as there are some very helpful classes in Cocoa. To store the credentials we can use the class NSURLCredential and add them to a NSURLProtectionSpace to map them to a host. Here is an example of it in action:

NSURLCredential *cred;
NSURLProtectionSpace *space;

cred = [NSURLCredential credentialWithUser:@"user"
space = [[NSURLProtectionSpace alloc] initWithHost:@"" 
                                             realm:@"Secure area"
[[NSURLCredentialStorage sharedCredentialStorage]
[space release];
[cred release];

That’s all. This way also requests in a UIWebView can be authenticated.