NSURLSession,HTTP基本身份验证和自签名证书

时间:2013-12-18 22:31:45

标签: basic-authentication nsurlsession

我使用HTTPS方案调用Web服务。要访问Web服务,我需要用户名和密码。我实现了http基本身份验证。 我总是得到401错误,我确信用户名和密码是正确的。这是我使用的代码(我在这里看到了这段代码:How can I pass credentials while using NSURLSession)。建议?谢谢!

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 个答案:

答案 0 :(得分:2)

对于基本身份验证,我没有设法使用文档描述的方式,但我可以完全按照文档说的不做,并直接在会话中设置标题。

这是Swift版本。

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

我认为您也可以直接在请求中设置它们。 Obj-C等效留给读者练习。

有一个good blog post here解释了如何使用凭证委托。