While working on a certain unnamed iPhone app lately I ran across the need to use basic authentication in communication with REST services. For something that seems to be such a fundamental need for mobile applications I figured most of the work would be done for me. Turns out that's not the case. A few details are left up to you, the Cocoa Touch programmer.

What Basic Authentication is

In order to implement basic authentication in Cocoa Touch it is important to understand how it works. Basic authentication tokens are essentially formatted into a string in the format:

username:password

They are then Base64-encoded and formatted into an "Authorization" HTTP header who's value looks like:

Basic c2NvdHQ6dGlnZXI=

where "c2NvdHQ6dGlnZXI=" is the encoded token pair and "Basic" is a hard-coded prependage.

Easy enough right? Encode username and password, slap it in the header and make the request.

What's not Provided by Cocoa Touch: Base64

I thought for sure I'd be able to leverage something out-of-the-box to handle the Base64 encoding. Surely I can do it by using some simple method or function somewhere. It'd just be a one-liner something-er-other, right? Right?? Wrong!

Nothing in Cocoa Touch natively provides you with Base64 encoding capabilities. You also don't have access to openssl on the iPhone via the SDK. In Cocoa Touch's defense I guess it never claimed to have the batteries included (my python & ruby soaked brain always expects everything to be done for me;)).

While I've seen suggestions to statically link openssl against your iPhone app it's not only overkill but presumably puts the responsibility on you to comply with U.S. export regulations (the cryptography in openssl is legally a munition in the states after all).

Besides, it's rather simple to implement Base64 yourself.

A Base64 Implementation

There are a number of implementations you can cherry-pick from elsewhere but in the spirit of demonstration I'll provide an example Base64 encoder that you can use in your project.

Contrary to the spirit of demonstration, however, I'm not going to explain it too much as it's not the subject of the post. If you need more background about the algorithm Ramkumar Menon wrote an excellent blog post about it. Also note that the code is arranged for readability, not conciseness.

static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
    +(char *)encode:(NSData *)plainText {
        // create an adequately sized buffer for the output.  every 3 bytes 
        // become four basically with padding to the next largest integer
        // divisible by four. 
        char * encodedText = malloc((((([plainText length] % 3) +
            [plainText length]) / 3) * 4) + 1);
        char* inputBuffer = malloc([plainText length]);
        inputBuffer = (char *)[plainText bytes];
    
        NSInteger i;
        NSInteger j = 0;
    
        // encode, this expands every 3 bytes to 4
        for(i = 0; i < [plainText length]; i += 3) {
            encodedText[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
            encodedText[j++] = alphabet[((inputBuffer[i] & 0x03) << 4)
                | ((inputBuffer[i + 1] & 0xF0) >> 4)];
    
            if(i + 1 >= [plainText length])
                // padding
                encodedText[j++] = '=';
            else 
                encodedText[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
                | ((inputBuffer[i + 2] & 0xC0) >> 6)];
    
            if(i + 2 >= [plainText length])
                // padding
                encodedText[j++] = '=';
            else
                encodedText[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
        }
        
        // terminate the string
        encodedText[j] = 0;
    
        return outputBuffer;
    }
@end

Creating and Using a Proper Request

Now that we're ready to speak the encoding that the webservers are expecting we can get down to business. Consider the following code which executes an authenticated request against a resource via a synchronous NSURLRequest. Adding an "Authorization" header with the appropriately formatted, Base64-encoded authentication tokens are all that's required to authenticate the request.

NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/"];
NSString userName = @"scott";
NSString password = @"tiger";

NSError *myError = nil;

// create a plaintext string in the format username:password
NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];

// employ the Base64 encoding above to encode the authentication tokens
char *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];

// create the contents of the header 
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", 
    [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
    cachePolicy: NSURLRequestReloadIgnoringCacheData  
    timeoutInterval: 3];   

// add the header to the request.  Here's the $$$!!!
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];

// perform the reqeust
NSURLResponse *response;

NSData *data = [NSURLConnection  
    sendSynchronousRequest: request  
    returningResponse: &response  
    error: &myError];  
*error = myError;

// POW, here's the content of the webserver's response.
NSString *result = [NSString stringWithCString:[data bytes] length:[data length]];

Conclusion

Aside from rolling-your-own (or snagging-someone-elses) Base64 implementation this isn't too bad.

To take it further you might employ NSURLCredential for storage of your authentication tokens.

Also if an asynchronous NSMutableURLRequest is used you can easily handle a webserver issuing a challenge by implementing the didReceiveAuthenticationChallenge message.

Created on 2010-01-24 13:01:00 UTC
 
0 Comments - Comment Feed - Permalink
Name
E mail (Private)
URL
Body
Human?
Tags:
.Net .net framework 4.0 ADO.NET AppleScript Astoria BI BeOS C C++ CAPTCHA Data Services EF GNOME GObject Groovy HTML Haiku JVM Java Lucene Mac MongoDB ORM Objective-C Operating Systems Oracle SSRS Solr VS 2010 Vala Web Services appengine c# clojure cloud clr cocoa touch concurrency couchdb cql cte curl database django dlr dynamic entity framework erlang exchange server filestream full-text functional go iPhone indexes ironpython ironruby jQuery linq lisp lucene monitoring natural language object oriented parallel performance podcasts powershell python rails refactoring remoting reporting services rs ruby scripting security setpolicies simpledb sql 2008 sql server stackless systems programming testing tools vb virtualization wave webdav windows xml