AFNetworking NTLM身份验证?

Ala*_*lan 3 authentication ntlm objective-c ios afnetworking

我正试图让AFNetworking工作,因为这是我的第一个必须处理客户端/服务器的应用程序,我试图从需要用户名/密码的HTTPS服务器中获取JSON.我有点迷上了应用程序,但它一直抛出一个401错误,我把它看起来是基本身份验证问题.

我基本上从AFNetworking那里获取了twitter示例并将其改编为我的项目.在AFHTTPClient的子类中,我在initWithBaseURL中添加了另一行,它仍然抛出错误.我要添加的行是setAuthorizationHeaderWithUsername

- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
    return nil;
}

[self registerHTTPOperationClass:[AFJSONRequestOperation class]];

// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
[self setAuthorizationHeaderWithUsername:@"myusername" password:@"my password"];

return self;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*iel 5

如果您尝试在AFNetworking中使用NTLM身份验证,则可以尝试以下操作:

AFNetworking通常通过提供对身份验证挑战的基于块的响应来支持NTLM身份验证(或基本上任何身份验证方法).

这里的一个代码示例(假设operation是一个AFHTTPRequestOperation,AFJSONRequestOperation等等).在开始操作之前,设置身份验证质询块,如下所示:

[operation setAuthenticationChallengeBlock:
 ^( NSURLConnection* connection, NSURLAuthenticationChallenge* challenge )
{
   if( [[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodNTLM )
   {
      if( [challenge previousFailureCount] > 0 )
      {
         // Avoid too many failed authentication attempts which could lock out the user
         [[challenge sender] cancelAuthenticationChallenge:challenge];
      }
      else
      {
         [[challenge sender] useCredential:[NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession] forAuthenticationChallenge:challenge];
      }
   }
   else
   {
      // Authenticate in other ways than NTLM if desired or cancel the auth like this:
      [[challenge sender] cancelAuthenticationChallenge:challenge];
   }
}];
Run Code Online (Sandbox Code Playgroud)

像往常一样启动或排队操作,这应该可以解决问题.

这基本上是Wayne Hartman 在其应用于AFNetworking的博客中描述的方法.