2
votes

I call a web service with the HTTPS scheme. To access to web service I need a username and password. I implemented the http basic authentication. I always get the 401 error and I am sure that username and password are correct. Here is the code I used (I saw this code here: How can I pass credentials while using NSURLSession). Suggestions? Thank you!

NSURL *url = [NSURL URLWithString:@"http://myurl...."];

NSString *user = @"userna,e";
NSString *password = @"password";
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent];

NSString *host = [url host];
NSInteger port = [[url port] integerValue];
NSString *protocol = [url scheme];

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];

NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setURLCredentialStorage:credentials];

NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
        NSLog(@"%d", httpResp.statusCode);
    }

}] resume];

...

// ONLY FOR SELF-SIGNED CERTIFICATE!!! DANGEROUS!!
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
1

1 Answers

2
votes

For basic auth I didn't manage to getting working with the way the docs described but I could just do exactly what the docs say not to do and set the header directly on the session.

This is the Swift version.

   let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
   sessionConfig.HTTPAdditionalHeaders = ["Authorization":"Basic fjdslkfsdfk="]

I think you can also set them directly on the request. Obj-C equivalent is left as an exercise for the reader.

There is a good blog post here that explains how the credential delegate should be used.