In this blog post I am going to show how you can make an HTTP request to a webserver that supports basic access authentication using Objective-C and the iOS framework. Regretfully, I don’t have the time to create an Xcode project as an example. But the information and code should give you an idea of how you can build basic access authentication support in your iOS code.
Before we dive into the code, let’s do a quick review of how basic access authentication works. Before an HTTP request is sent to the server, we need to append an HTTP header called Authorization to the request. Here are the steps to generating the Authorization HTTP header:
Using username = myusername and password = mypassword as reference.
- Concatenate user name + colon + password. ie. “myusername:mypassword”
- Encode the concatenated string with the base64 algorithm. ie. “myusername:mypassword becomes” “bXl1c2VybmFtZTpteXBhc3N3b3Jk”
- Append the Base64 encoded string to the “Basic ” string. ie. “Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk”
- Finally assign the value to the Authorization header
In Objective-C code, the above logic is translated to:
NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"myusername", @"mypassword"]; NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]]; [request setValue:authValue forHTTPHeaderField:@"Authorization"];
Just one problem, NSData doesn’t inherently support Base64 encoding. We need to add Base64 encoding algorithm to NSData via Category, a mechanism Objective-C that allows programmers to extend an existing class without subclassing it. Anyway, you can download the Base64 encoding code below.
Credits and Reference:
- Cocoadev/BaseSixyFour (there are a few other Base64 algorithms posted here)
- StackOverflow on NSURLConnection and basic access authentication
Note that you can certainly implement Base64 encoding using C functions or by other means. But I find Category most intuitive to achieving our goal.
If you are still stuck, use the curl command on a shell to troubleshoot. Here are some examples:
% curl -v -H 'Authorization: Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk' 'http://host/path'
% curl -v --trace-ascii dump.txt 'http://myusername:mypassword@host/path'