6

I am in a situation where I need to send authentication (basic HTTP Authentication) to a server but the server does not send me a challenge first. This has been tracked down to be a duplicate of the wget switch --auth-no-challenge. My problem is, I do not see any way to get NSURL to do this.

I have implemented basic authentication in my NSURLConnection delegate but the -connection: didReceiveAuthenticationChallenge: method is not getting called.

Is there any way to force this call or to embed the authentication information for this strange situation?

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182

3 Answers3

9

I believe you can add the username and password to the NSURL

Example

NSURL *url = [NSURL URLWithString:@"http://username:password@some.host.com/"];
epatel
  • 45,805
  • 17
  • 110
  • 144
8

You can add the authorization information to the request manually by adding it to the request header like so:

NSString *authString = [[[NSString stringWithFormat:@"%@:%@",user, password] dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];        
[request setValue:[NSString stringWithFormat:@"Basic %@", authString] forHTTPHeaderField:@"Authorization"]; 

Where request is your NSMutableURLRequest and user/password are your respective username and password NSString's

I've been using this approach with an API from the iphone where the extra challenge is not being initiated by the server.

paulthenerd
  • 9,487
  • 2
  • 35
  • 29
  • I get an error, when I want to use your solution: NSData does not respond to base64Encoding". Have you added this method yourself? – Tim Büthe May 08 '10 at 12:14
  • Found NSDataAdditions, including base64Encoding in this answer: http://stackoverflow.com/questions/1417893/encrypted-nsdata-to-nsstring-in-obj-c/1417947#1417947 – Tim Büthe May 08 '10 at 12:20
  • Hi Tim, Yes I have been using NSDataAdditions from the colloquy project – paulthenerd May 09 '10 at 21:09
0

Just stumbled upon this post, and event though it's been a few years I just implemented this functionality in iOS7 for my app using built-in base64-encoding without any 3rd-party libs.

For what it's worth;

NSString *credentials = [NSString stringWithFormat:@"%@:%@", username, password];
NSData* credentialsData = [NSData dataWithBytes:[credentials UTF8String] length:strlen([credentials UTF8String])];
credentials = [credentialsData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *authStr = [NSString stringWithFormat:@"Basic %@", credentials];
[urlRequest setValue:authStr forHTTPHeaderField:@"Authorization"];
Markus Millfjord
  • 707
  • 1
  • 6
  • 26