带有基本身份验证挑战的NSURLSession [英] NSURLSession With Basic Authentication Challenge
问题描述
我搜索了stackoverflow中所有可用的解决方案.仍然对此感到困惑.
如果我有任何错误,请指出我.我收到401错误.
I searched all the solution avaliable in stackoverflow. Still confused with this.
Please point me if i am doing any mistake. I am getting 401 error.
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://qa.api.xxxxxx.com/v0/jobs/93033"]];
NSString *authStr = @"xxxxxxxx:xxxxxxxxxxx";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
request.HTTPMethod = @"GET";
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
//create the task
NSURLSessionDataTask* task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@",json);
dispatch_async(dispatch_get_main_queue(), ^{
});
} else {
// failure: do something else on failure
NSLog(@"httpResponse code: %@", [NSString stringWithFormat:@"%ld", (unsigned long)httpResponse.statusCode]);
NSLog(@"httpResponse head: %@", httpResponse.allHeaderFields);
return;
}
}];
[task resume];
推荐答案
也许您的请求通过NSURLSession自动生成的没有授权标头的新请求重定向到其他地方.
Perhaps your request is redirected to some where else with a new request which is auto-generated by NSURLSession without authorization header.
您可以使用Wireshark跟踪您的请求是否确实发生了.
You could use Wireshark to track your request exactly happened.
如果您的请求被重定向,则可以使用以下方法来确保新请求正在发送身份验证信息:
If your request is redirected, you can use the following methods to make sure the new request is sending with authentication information:
1.使用委托方法处理身份验证
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
if (challenge.previousFailureCount > 1) {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}else {
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
password:@"pswd"
persistence:NSURLCredentialPersistenceForSession];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
}
应该是处理身份验证的最佳方法.
Should be best way to handle authentications.
2.使用委托方法将身份验证标头添加到新请求中
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest *))completionHandler {
NSMutableURLRequest *newRequest = request.mutableCopy;
// Add authentication header here.
completionHandler(newRequest);
}
当您的请求被重定向时,再次添加身份验证标头.
Add authentication header again when your request gets redirect.
3.将身份验证标头设置为NSURLSession的附加标头
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Authorization":@"Basic xxxxxxxxxxxxxxxxxx"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
确保NSURLSession使用该身份验证标头创建新请求.
Make sure NSURLSession creates new request with that authentication header.
这篇关于带有基本身份验证挑战的NSURLSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!