0

Is it possible to use the sendAsynchronousRequest of NSURLConnection knowing the requested url will have a redirect and all request must also use basic auth?

I am getting the following error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)

I did write some code using the NSURLConnectionDelegate and modified the redirect request to add the basic auth in the header and that worked.

So I'm guessing it has something to do with the authentication not being set on the second request. The same with the Delegate, If I didn't set the basic auth on the redirect request things were failing with a HTTP 401 unauthorized

Deepesh
  • 8,065
  • 3
  • 28
  • 45
pdiddy
  • 6,217
  • 10
  • 50
  • 111

1 Answers1

0

It is possible I believe as I am doing it currently, here's my code, the trick is to set the header for "Authorization" with "Basic base64encodedmethod(username:password)"

//SETUP URL
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://YOURURLHERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:90.0];

//Get the username & password - then encode the values with Base64 (i googled for a library)
 NSString *userAndPassword = [NSString stringWithFormat:@"%@:%@",userName,password];
    NSString *encodedString = [userAndPassword base64EncodedString];

//Set the Authorization header which will now let your service calls pass basic authentication
    [request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"];

//Setup a queue and call the async request - remember to do items in your block on the 
//main thread if it's for things like showing/hiding items as other threads will not run that code when you're expecting it

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//your code block here 
}];

I believe that answers your question, now I just need to find out how to delete that authentication so I can log the user out as I'm building this for a secure legal site. Any help there would be appreciated

Stu P.
  • 1,365
  • 1
  • 14
  • 31