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?
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