首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用NSURLCredential的AFNetworking

使用NSURLCredential的AFNetworking
EN

Stack Overflow用户
提问于 2015-04-11 03:00:06
回答 1查看 1.1K关注 0票数 17

我有3个方法,UserLogin,Login和LogoutButtonPressed:

UserLogin:我正在使用AFNetworking通过NSURLCredential连接到经过Windows身份验证的URL:

代码语言:javascript
复制
-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{

   NSURL *url = [NSURL URLWithString:kIP];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];

    NSURLCredential *credential = [NSURLCredential
                                   credentialWithUser:user
                                   password:password
                                   persistence:NSURLCredentialPersistenceForSession];

    [operation setCredential:credential];


    [[NSOperationQueue mainQueue] addOperation:operation];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (completionHandler) {
            completionHandler(responseObject, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        if (completionHandler) {
            completionHandler(nil, error);
        }

    }];

    [operation start];

}

此方法正由Login方法调用:

代码语言:javascript
复制
- (void)Login
{
    NSString *rawString = [self.idTextField text];
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    [self.idTextField setText:[rawString stringByTrimmingCharactersInSet:whitespace]];


    [userName UserLogin:self.idTextField.text andPassWordExists:self.passwordTextField.text completionHandler:^(id responseObject, NSError *error) {
        if (responseObject) {

                [self.idTextField removeFromSuperview];
                [self.passwordTextField removeFromSuperview];
                [self.loginButton removeFromSuperview];
                self.idTextField = nil;
                self.passwordTextField = nil;
                //self.loginButton = nil;


                [self CreateMenu];



                [indicatorView stopAnimating];
                [indicatorView removeFromSuperview];
                indicatorView = nil;
                [loadingView removeFromSuperview];
                loadingView = nil;
        }else{


            [self CustomAlert:@"Sorry Login Failed, User and/or Passsword Incorrect"];

            [indicatorView stopAnimating];
            [indicatorView removeFromSuperview];
            indicatorView = nil;
            [loadingView removeFromSuperview];
            loadingView = nil;

        }
    }];

}

我正在尝试清除与LogoutButtonPressed的会话:

代码语言:javascript
复制
- (void)LogoutButtonPressed
{

    //@TODO: Fix Logout

    NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];

    if ([credentialsDict count] > 0) {
        NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
        id urlProtectionSpace;

        while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
            NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
            id userNameCred;

            while (userNameCred = [userNameEnumerator nextObject]) {
                NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userNameCred];
                NSLog(@"cred to be removed: %@", cred);
                [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
            }
        }
    }
}

我从这个例子中得到了下面的代码:http://www.springenwerk.com/2008/11/i-am-currently-building-iphone.html

现在我的问题是,当我触发注销按钮,然后去触发没有凭据的登录方法时,我仍然可以登录,如果我注销,那么等待2-3分钟,没有凭据的登录我无法登录。为什么要这样做,就好像证书还在保存一样。请帮帮忙。

更新

我试图清除LogoutButtonPressed中的缓存、cookies和creds:

代码语言:javascript
复制
NSURLCache *sharedCache = [NSURLCache sharedURLCache];
[sharedCache removeAllCachedResponses];

NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [cookieStorage cookies];
id cookie;
for (cookie in cookies) {
    [cookieStorage deleteCookie:cookie];
}

NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
if ([credentialsDict count] > 0) {
    NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
    id urlProtectionSpace;
    while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
        NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
        id userNameCreds;
        while (userNameCreds = [userNameEnumerator nextObject]) {
            NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userNameCreds];
            [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
        }
    }
}

但它仍然不起作用。

我也尝试过清除AuthorizationHeader和cancelingAllOperations,但仍然没有结果,在注销后,我仍然可以使用错误的或没有凭证的方式登录:

代码语言:javascript
复制
NSURLCache *sharedCache = [NSURLCache sharedURLCache];
    [sharedCache removeAllCachedResponses];

    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookies = [cookieStorage cookies];
    id cookie;
    for (cookie in cookies) {
        [cookieStorage deleteCookie:cookie];
    }

    NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
    if ([credentialsDict count] > 0) {
        NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
        id urlProtectionSpace;
        while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
            NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
            id userNameCreds;
            while (userNameCreds = [userNameEnumerator nextObject]) {
                NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userNameCreds];
                [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
            }
        }
    }

    NSURL *url = [NSURL URLWithString:kIP];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer;
    [requestSerializer clearAuthorizationHeader];

    AFHTTPRequestOperationManager  *httpClient = [[AFHTTPRequestOperationManager  alloc] initWithBaseURL:url];
    [[httpClient operationQueue] cancelAllOperations];
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-15 22:19:27

通过在URL末尾添加一个随机数,可以轻松解决此问题:

代码语言:javascript
复制
-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{
   NSInteger randomNumber = arc4random() % 999;

   NSString *requestURL = [NSString stringWithFormat:@"%@?cache=%ld",kIP,(long)randomNumber];

   NSURL *url = [NSURL URLWithString:requestURL];

   NSURLRequest *request = [NSURLRequest requestWithURL:url];
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                         initWithRequest:request];

   NSURLCredential *credential = [NSURLCredential
                                   credentialWithUser:user
                                   password:password
                                   persistence:NSURLCredentialPersistenceForSession];


    [operation setCredential:credential];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:operation];


    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (completionHandler) {
            completionHandler(responseObject, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        if (completionHandler) {
            completionHandler(nil, error);
        }

    }];

    [operation start];

}

并确保在您调用的所有URL的末尾都有一个随机数。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29568853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档