NSURLSession和身份验证与凭据

时间:2015-10-13 16:43:19

标签: objective-c ios9 nsurlsession

我正在尝试从需要使用NSURLSession进行身份验证的Web服务器中获取数据。我尝试了几种不同的方式而没有运气。这是我到目前为止所拥有的。它正在进入协议方法didReceiveChallenge,但似乎没有进行身份验证。我收到的数据是空的。

我已检查用户名/密码是否正确。我已经仔细检查了URL是否正确,通过在safari中访问该URL并手动输入凭据,我看到了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");
}

这是我的输出。

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

感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

我可能会尝试将didReceiveChallenge修改为类似下面的内容

- (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");
    }
}

答案 1 :(得分:0)

- (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);
    }
}