Friday, 29 May 2015

HTTP basic access authentication

In this RESTful world, access to any modern data website is restricted with some kind of authenticatio.Several known open authentication mechanisms used on Web.
When a client requests a server for a resource,  the server checks if the resource is protected and if it is, it sends a “401 Unauthorized” response back with WWW-Authenticate in the header. The WWW-Authenticate header field might contain a value, which is either “Basic” or “Digest” depending on the  mechanism.
Before an HTTP request is sent to the server, we need to append an HTTP header called Authorization to the request.  For basic authentication, this is usually “base64(username:password)” in the Authorization header field.

Here are the steps to generating the Authorization HTTP header:
Concatenate user name + colon + password.
Encode the concatenated string with the base64 algorithm
Append the Base64 encoded string to the “Basic ” string.
Finally assign the value to the Authorization header.

 In Objective C code
NSString *userName = @"";
NSString *password = @"";
NSString *authString = [NSString stringWithFormat:@"%@:%@",userName,password];
 

NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", encodedLoginData];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];