进行NTLM Web服务调用的适当NSURLConnection / Credential模式是什么?

时间:2014-06-12 15:14:53

标签: objective-c nsurlconnection credentials ntlm nsurlcredential

我有一个“传统”企业iPad应用程序,需要使用 NTLM 身份验证在其生命周期内进行许多不同的Web服务调用。在启动应用程序时,我预计会从密钥链中获取用户名和密码(由于密钥链没有用户名,应用程序会在第一次使用时保存该密钥链,然后在密码无法工作时更新更新)。

启动时,需要各种Web服务调用来获取应用程序的初始数据。然后,用户将看到一个选项卡式控制器,以选择他们想要的功能,这当然会进行更多的Web服务调用。

我相信我有一个策略来处理每个通过自定义数据委托接收数据的类,如此StackOverflow答案(How do you return from an asynchronous NSURLConnection to the calling class?)中所示。但是,我仍然对如何正确使用-(void)useCredential:(NSURLCredential *)credential forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge功能感到困惑。

在didReceiveAuthenticationChallenge中,我有这样的代码

[[challenge sender]  useCredential:[NSURLCredential credentialWithUser:@"myusername"
                          password:@"mypassword"
                       persistence:NSURLCredentialPersistencePermanent]
        forAuthenticationChallenge:challenge];

由于我正在设置永久持久性,因此我希望不必在功能中不断传递用户名和密码。是否有一种模式用于初始设置用户的NTLM凭证(和/或检查它们是否已经存在),然后只使用“永久”凭据进行后续Web服务调用?

此外,作为第二个问题/部分。在Objective-C应用程序中传递用户名/密码的适当/优雅方法是什么?我正在考虑全局var或单例实例(对于几个需要的var来说,这似乎有些过分了。)

1 个答案:

答案 0 :(得分:0)

已经有一段时间了,因为我们已经解决了这个问题并成功解决了这个问题。我觉得是时候在这里提出答案了。下面的代码属于它自己的类,不会开箱即用,但应该让你有很长的路要走。在大多数情况下,这一切都应该可以正常工作,但您只需要确保警报视图,数据存储等各个区域都按照您的需要进行设置。

我们理解Objective-C& S的方式的一个主要障碍iOS处理NTLM通信正在弄清楚它与URL通信的正常过程。

首次与网址联系是匿名进行的。当然,在Windows安全环境中,这将失败。这是应用程序将再次尝试联系URL时,但这次使用的是已经存在于密钥链上的该URL的任何凭据,并使用willSendRequestForAuthenticationChallenge方法。这对我们来说非常混乱,因为这种方法直到第一次呼叫失败后才开火。它最终让我们意识到第一次呼叫是匿名的。

您在此处看到的部分模式是,将使用钥匙串上已有的任何凭据尝试连接。如果那些失败/丢失,那么我们将弹出一个请求用户输入用户名和密码的视图,然后我们重试。

我们需要考虑的一些特性,因为您将在整个代码中看到这些特性。经过多次迭代和大量测试才能保持稳定。其中大部分是基于在互联网上发布的模式,这些模式几乎完成了我们想要做的事情,但并没有把我们带到那里。

我们做的代码概括了GET / POST调用。这是我向StackOverflow发表的第一篇主要代码文章,如果我错过了一些约定,我会道歉,并且当我引起我的注意时,我会纠正我需要的内容。

#import "MYDataFeeder.h"
#import "MYAppDelegate.h"
#import "MYDataStore.h"
#import "MYAuthenticationAlertView.h"
#import "MYExtensions.h"

@interface MYDataFeeder () <NSURLConnectionDelegate>
    @property (strong, nonatomic) void (^needAuthBlock)(NSString *, NSString *);
    @property (strong, nonatomic) void (^successBlock)(NSData *);
    @property (strong, nonatomic) void (^errorBlock)(NSError *);
@end


@implementation MYDataFeeder{
    NSMutableData *_responseData;
    NSString *_userName;
    NSString *_password;
    NSString *_urlPath;
    BOOL _hasQueryString;
}

+ (void)get: (NSString *)requestString
   userName: (NSString *)userName
   password: (NSString *)password
hasNewCredentials: (BOOL)hasNewCredentials
successBlock: (void (^)(NSData *))successBlock
 errorBlock: (void (^)(NSError *))errorBlock
needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock
{
    MYDataFeeder *x = [[MYDataFeeder alloc] initWithGetRequest:requestString userName:userName password:password hasNewCredentials:hasNewCredentials successBlock:successBlock errorBlock:errorBlock needAuthBlock:needAuthBlock];
}

+ (void)post: (NSString *)requestString
    userName: (NSString *)userName
    password: (NSString *)password
hasNewCredentials: (BOOL)hasNewCredentials
  jsonString: (NSString *)jsonString
successBlock: (void (^)(NSData *))successBlock
  errorBlock: (void (^)(NSError *))errorBlock
needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock
{
    MYDataFeeder *x = [[MYDataFeeder alloc] initWithPostRequest:requestString userName:userName password:password hasNewCredentials:hasNewCredentials jsonString:jsonString successBlock:successBlock errorBlock:errorBlock needAuthBlock:needAuthBlock];
}

- (instancetype)initWithGetRequest: (NSString *)requestString
                          userName: (NSString *)userName
                          password: (NSString *)password
                 hasNewCredentials: (BOOL)hasNewCredentials
                      successBlock: (void (^)(NSData *))successBlock
                        errorBlock: (void (^)(NSError *))errorBlock
                     needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock
{
    return [self initWithRequest:requestString userName:userName password:password hasNewCredentials:hasNewCredentials isPost:NO jsonString:nil successBlock:successBlock errorBlock:errorBlock needAuthBlock:needAuthBlock];
}

-(instancetype)initWithPostRequest: (NSString *)requestString
                          userName: (NSString *)userName
                          password: (NSString *)password
                 hasNewCredentials: (BOOL)hasNewCredentials
                        jsonString: (NSString *)jsonString
                      successBlock: (void (^)(NSData *))successBlock
                        errorBlock: (void (^)(NSError *))errorBlock
                     needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock
{
    return [self initWithRequest:requestString userName:userName password:password hasNewCredentials:hasNewCredentials isPost:YES jsonString:jsonString successBlock:successBlock errorBlock:errorBlock needAuthBlock:needAuthBlock];
}

//Used for NTLM authentication when user/pwd needs updating
- (instancetype)initWithRequest: (NSString *)requestString
                       userName: (NSString *)userName
                       password: (NSString *)password
              hasNewCredentials: (BOOL)hasNewCredentials
                         isPost: (BOOL)isPost
                       jsonString: (NSString *)jsonString
                   successBlock: (void (^)(NSData *))successBlock
                     errorBlock: (void (^)(NSError *))errorBlock
                  needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock //delegate:(id<MYDataFeederDelegate>)delegate
{
    self = [super init];

    requestString = [requestString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    if(self) {
        if (!errorBlock || !successBlock || !needAuthBlock) {
            [NSException raise:@"MYDataFeeder Error" format:@"Missing one or more execution blocks. Need Success, Error, and NeedAuth blocks."];
        }

        _responseData = [NSMutableData new];
        _userName = userName;
        _password = password;
        _successBlock = successBlock;
        _hasNewCredentials = hasNewCredentials;
        _errorBlock = errorBlock;
        _needAuthBlock = needAuthBlock;
        NSString *host = [MYDataStore sharedStore].host; //Get the host string
        int port = [MYDataStore sharedStore].port; //Get the port value
        NSString *portString = @"";

        if (port > 0) {
            portString = [NSString stringWithFormat:@":%i", port];
        }

        requestString = [NSString stringWithFormat:@"%@%@/%@", host, portString, requestString];
        NSURL *url = [NSURL URLWithString:requestString];

        NSString *absoluteURLPath = [url absoluteString];
        NSUInteger queryLength = [[url query] length];
        _hasQueryString = queryLength > 0;
        _urlPath = (queryLength ? [absoluteURLPath substringToIndex:[absoluteURLPath length] - (queryLength + 1)] : absoluteURLPath);

        NSTimeInterval timeInterval = 60; //seconds (60 default)

        NSMutableURLRequest *request;

        if (isPost) {
            request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeInterval];

            NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

            [request setHTTPMethod:@"POST"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)requestData.length] forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody: requestData];
            [request setHTTPShouldHandleCookies:YES];
        }
        else {
            request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:timeInterval];
        }

        NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    }

    return self;
}

- (instancetype)initWithRequest: (NSString *)requestString
                   successBlock: (void (^)(NSData *))successBlock
                     errorBlock: (void (^)(NSError *))errorBlock
                  needAuthBlock: (void (^)(NSString *, NSString *))needAuthBlock //delegate:(id<MYDataFeederDelegate>)delegate
{
    return [self initWithRequest:requestString userName:NULL password:NULL hasNewCredentials:NO isPost:NO jsonString:nil successBlock:successBlock errorBlock:errorBlock needAuthBlock:needAuthBlock]; //delegate:delegate];
}

#pragma mark - Connection Events

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return YES;
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection {
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (response){
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        NSInteger code = httpResponse.statusCode;

        if (code == 401){
            NSLog(@"received 401 response");
            [MYAuthenticationAlertView showWithCallback:_needAuthBlock];
            [connection cancel];
        }
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    _successBlock(_responseData);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_responseData appendData:data];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    _errorBlock(error);
}

- (void) connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM])
    {
        BOOL hasConnectionCredentials = [[MYDataStore sharedStore] hasConnectionCredentials]; //Determines if there's already credentials existing (see method stub below)
        long previousFailureCount = [challenge previousFailureCount];

        BOOL hasFailedAuth = NO;

        //If the application has already gotten credentials at least once, then see if there's a response failure...
        if (hasConnectionCredentials){
            //Determine if this URL (sans querystring) has already been called; if not, then assume the URL can be called, otherwise there's probably an error...
            if ([[MYDataStore sharedStore] isURLUsed:_urlPath addURL:YES] && !_hasQueryString){
                NSURLResponse *failureResponse = [challenge failureResponse];

                if (failureResponse){
                    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)[challenge failureResponse];
                    long code = [httpResponse statusCode];

                    if (code == 401){
                        hasFailedAuth = YES;
                    }
                }
            }
        }
        else{
            //Need to get user's credentials for authentication...
            NSLog(@"Does not have proper Credentials; possible auto-retry with proper protection space.");
        }

        /*    This is very, very important to check.  Depending on how your security policies are setup, you could lock your user out of his or her account by trying to use the wrong credentials too many times in a row.    */
        if (!_hasNewCredentials && ((previousFailureCount > 0) || hasFailedAuth))
        {
            NSLog(@"prompt for new creds");
            NSLog(@"Previous Failure Count: %li", previousFailureCount);
            [[challenge sender] cancelAuthenticationChallenge:challenge];
            [MYAuthenticationAlertView showWithCallback:_needAuthBlock];
            [connection cancel];
        }
        else
        {
            if (_hasNewCredentials){
                //If there's new credential information and failures, then request new credentials again...
                if (previousFailureCount > 0) {
                    NSLog(@"new creds failed");
                    [MYAuthenticationAlertView showWithCallback:_needAuthBlock];
                    [connection cancel];
                } else {
                    NSLog(@"use new creds");
                    //If there's new credential information and no failures, then pass them through...
                    [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:_userName password:_password persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge];
                }
            } else {
                NSLog(@"use stored creds");
                //...otherwise, use any stored credentials to call URL...
                [[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
            }
        }
    }
    else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { // server trust challenge
        // make sure challenge came from environment host
        if ([[MYDataStore sharedStore].host containsString:challenge.protectionSpace.host]) {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        }
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
    else {
        // request has failed
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

@end

-(BOOL) hasConnectionCredentials
{
    NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
    return ([credentialsDict count] > 0);
}

//Sample use of Data Feeder and blocks:
-(void)myMethodToGetDataWithUserName:(NSString*)userName password:(NSString*)password{
//do stuff here
[MYDataFeeder get:@"myURL"
userName:userName
password:password
hasNewCredentials:(userName != nil)
successBlock:^(NSData *response){ [self processResponse:response]; }
            errorBlock:^(NSError *error) { NSLog(@"URL Error: %@", error); }
         needAuthBlock:^(NSString *userName, NSString *password) { [self myMethodToGetDataWithUserName:username withPassword:password]; }
];
}

//The needAuthBlock recalls the same method but now passing in user name and password that was queried from within an AlertView called from within the original DataFeeder call