如何使用带有摘要式身份验证的AFNetworking 2 [英] How to use AFNetworking 2 with Digest Authentication

查看:73
本文介绍了如何使用带有摘要式身份验证的AFNetworking 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在搜索带有摘要式身份验证的AFNetworking 2",但没有找到有用的讨论(

I've been searching for "AFNetworking 2 with Digest Authentication" for a while and haven't found useful discussions about it (except this one, but unfortunately it looks like it's for AFNetworking 1).

这是我的未经身份验证的代码:

Here's my code without authentication:

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

摘要验证代码在哪里以及如何插入?

Where and how can Digest Auth code kick in?

推荐答案

我最近升级到了AFNetworking-3,现在不再支持 NSURLConnection .

I recently upgrade to AFNetworking-3, there's no NSURLConnection support anymore.

当我更改为 NSURLSession 时,我遇到了同样的问题.

When I change to NSURLSession, I got same problem.

谢谢鲍勃,编辑AFNetworkings AFURLSessionManager.m 对我来说效果很好.

Thank you bob, edit AFNetworkings AFURLSessionManager.m works fine for me.

但是,在那之后,我发现如果设置了 self.taskDidReceiveAuthenticationChallenge 的简便方法,我们就不必更改AFNetworkings代码.

But after that, I found a easier way if self.taskDidReceiveAuthenticationChallenge is set, we don't have to change AFNetworkings code.

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSURLCredential *myCredential = [[NSURLCredential alloc] initWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession];

[manager setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
    if (challenge.previousFailureCount == 0) {
        *credential = myCredential;
        return NSURLSessionAuthChallengeUseCredential;
    } else {
        return NSURLSessionAuthChallengePerformDefaultHandling;
    }
}];

这篇关于如何使用带有摘要式身份验证的AFNetworking 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆