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!!@webservice.com/precious/data

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"
                                  password:@"very!secure$password!!"
                               persistence:NSURLCredentialPersistenceForSession]; 
space = [[NSURLProtectionSpace alloc] initWithHost:@"webservice.com" 
                                              port:80 
                                          protocol:@"http" 
                                             realm:@"Secure area"
                              authenticationMethod:nil]; 
[[NSURLCredentialStorage sharedCredentialStorage]
      setDefaultCredential:cred 
        forProtectionSpace:space];
[space release];
[cred release];

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