我一直在搜索“AFNetworking 2 with Digest Authentication”有一段时间了,但没有找到关于它的有用讨论(除了 this one ,但不幸的是它看起来像是针对 AFNetworking 1)。
这是我未经身份验证的代码:
NSString* apiURL = @"https://api.example.com/WS.asmx";
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager
GET:apiURL
parameters: [NSDictionary dictionaryWithObjectsAndKeys:@"ID", 1234 , nil]
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"WS request failed: %@", error);
}
];
Digest Auth 代码可以在何处以及如何启动?
最佳答案
这个问题有点老了,但我不得不这样做,但我找不到任何内置的方法来处理它。 我使用的解决方案是编辑 AFNetworkings AFURLSessionManager.m。 基本上,您修改此委托(delegate)方法以支持 http 摘要,这是一个完整示例。
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
if (self.taskDidReceiveAuthenticationChallenge) {
disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
} else {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
disposition = NSURLSessionAuthChallengeUseCredential;
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
NSDictionary *userkeys = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:challenge.protectionSpace];
credential = [userkeys objectForKey:(NSString *)[[userkeys allKeys] objectAtIndex: 0]];
if (credential) {
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
}else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
}
if (completionHandler) {
completionHandler(disposition, credential);
}
}
在此挑战之前,您需要将凭据添加到 sharedCredentialStorage。 您可以查看苹果文档,因为它相当简单,但要确保保护空间完全匹配,包括领域。 我希望它对某人有所帮助。
关于objective-c - 如何通过摘要身份验证使用 AFNetworking 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051250/