iPhone: How to Get Basic Authentication to HTTPS Web Service Using NSURLCredential

Ian1971 picture Ian1971 · Feb 24, 2010 · Viewed 11.8k times · Source

I am trying to call an https web service (RESTful) using basic authentication. It works fine if I put the credentials in the url itself but I would rather add it to the request so that the password does not appear, for instance in an exception.

I am using the following code:

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
                                                             password:@"mypassword"
                                                          persistence:NSURLCredentialPersistenceForSession];

    NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                             initWithHost:@"example.com"
                                             port:443
                                             protocol:@"https"
                                             realm:nil
                                             authenticationMethod:NSURLAuthenticationMethodHTTPBasic];


    [[NSURLCredentialStorage sharedCredentialStorage]  setDefaultCredential:credential
                                                        forProtectionSpace:protectionSpace];

    NSURLConnection *theConnection = [NSURLConnection  connectionWithRequest:theRequest delegate:self];

but it does not work. The didReceiveAuthenticationChallenge delegate method gets called and I can add a credential there but ideally I would send it with the request.

Any ideas?

Answer

lostInTransit picture lostInTransit · Mar 9, 2010

Try sending the credentials in the header if it is basic authentication. Works for me every time.

For sending the username and password in the header of the request

NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalAuth = base64 of authString;

In your request, add a header with the field name Authorization and value "Basic " + finalAuth