Wednesday, May 11, 2016

Objective C Basic Authentication Challenge (NSURLAuthenticationMethodHTTPBasic)

If we get authentication challenge as NSURLAuthenticationMethodHTTPBasic in your  authentication challenge delegate method using NSURLConnection/NSURLSession, We need to pass the credentials in the 'Autherization' header field of the request.

Here is the objective C code to convert the user credentials to BASIC format.

   NSString *username = @"username";
   NSString *password = @"password";

   NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];

   NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];

   NSString *authValue = [authData base64EncodedStringWithOptions:0];

   [request setValue:[NSString stringWithFormat:@"Basic %@",authValue]  


If you look at the code, It's a 4 step process.

  1. We need to place the colon in between username and password.
  2. Convert the above resulted string to data using ASCII Encoding.
  3. Convert the above resulted data into string using Base64 Encoding.
  4. Finally, Add Basic as a prefix to the above resulted string with a space in between.


Hope this post is useful. Feel free to comment incase of any queries.