Water4Fun
Water4Fun

Reputation: 43

NSURLSession and Authentication with credentials

I am trying to grab data from a web server that requires authentication using NSURLSession. I have tried a couple of different ways and no luck. Here is what I have so far. It is getting to the protocol method didReceiveChallenge, but doesn't seem to be authenticating. And the data I receive back is null.

I have checked the username/password they are correct. And I have double checked the URL is correct, by going to that URL in safari and manually entering the credentials and I see the JSON.

@interface PlaylistData1b() <NSURLSessionDataDelegate, NSURLSessionDelegate>
@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic, strong) NSString *requestString;
@end

@implementation PlaylistData1b

- (instancetype)initWithURL:(NSString *)urlString
{
    self = [super init];
    if(self){
        _requestString = urlString;
    }
    return self;
}
-(void)log
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    _session = [NSURLSession sessionWithConfiguration:config
                                             delegate:self
                                        delegateQueue:nil];
    [self fetchData];
}

-(void)fetchData
{
    NSString *requestString = _requestString;
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSURLSessionDataTask *dataTask =
        [self.session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"JSON: %@", jsonObject);
        }];

    [dataTask resume];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    NSURLCredential *cred = [NSURLCredential credentialWithUser:username
                                                       password:password
                                                    persistence:NSURLCredentialPersistenceNone];
    [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
    completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
    NSLog(@"Finished Challenge");
}

and here is my output.

2015-10-12 15:03:57.322 GetPlaylistData[7040:138551] Finished Challenge
2015-10-12 15:04:33.321 GetPlaylistData[7040:138788] JSON: (null)

Any help is appreciated. Thanks.

Upvotes: 4

Views: 4968

Answers (2)

Roman Solodyashkin
Roman Solodyashkin

Reputation: 829

- (void)digestAuthForTask:(NSURLSessionTask*)task{
    NSURL *url = task.originalRequest.URL;
    NSURLCredential *cred =
    [NSURLCredential credentialWithUser:@"user-xxx"
                               password:@"user-password-xxx"
                            persistence:NSURLCredentialPersistenceForSession];
    NSURLProtectionSpace *space =
    [[NSURLProtectionSpace alloc] initWithHost:url.host
                                          port:url.port.integerValue
                                      protocol:url.scheme
                                         realm:nil
                          authenticationMethod:NSURLAuthenticationMethodHTTPDigest];
    [NSURLCredentialStorage.sharedCredentialStorage setCredential:cred
                                               forProtectionSpace:space
                                                             task:task];
    [task resume];
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,   NSURLCredential *credential))completionHandler
{
    NSString *authMtd = challenge.protectionSpace.authenticationMethod;
    if ([authMtd isEqualToString: NSURLAuthenticationMethodHTTPDigest]) {
        if (!challenge.proposedCredential){
            [NSURLCredentialStorage.sharedCredentialStorage getDefaultCredentialForProtectionSpace:challenge.protectionSpace
                                                                                              task:task
                                                                                 completionHandler:^(NSURLCredential * _Nullable credential) {
                if (credential){
                    [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
                completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
                }
                else{
                    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
                completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
                }
            }];
        }
        else{
            [challenge.sender useCredential:challenge.proposedCredential forAuthenticationChallenge:challenge];
            completionHandler(NSURLSessionAuthChallengeUseCredential, challenge.proposedCredential);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

Upvotes: 0

Subbu
Subbu

Reputation: 2148

I'd probably try modifying the didReceiveChallenge to something like the below

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    NSString *authMethod = [[challenge protectionSpace] authenticationMethod];

    if ([authMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
         completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    } else {
        NSURLCredential *cred = [NSURLCredential credentialWithUser:username
                                                           password:password
                                                        persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
        completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
        NSLog(@"Finished Challenge");
    }
}

Upvotes: 4

Related Questions