使用NSURLCredential进行AFNetworking

用户名

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

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

-(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方法调用:

- (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清除会话:

- (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中的缓存,cookie和凭据:

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,仍然一无所获,注销后我仍然能够以错误或没有信誉的方式登录:

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];
用户名

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

-(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的末尾都有一个随机数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用AFNetworking进行图像缓存

来自分类Dev

使用AFNetworking进行JSON序列化

来自分类Dev

使用AFNetworking进行多部分PUT请求

来自分类Dev

如何使用AFNetworking进行JSON解析

来自分类Dev

如何使用AFNetworking-2.0进行JSON编码的GET请求?

来自分类Dev

使用AFHTTPRequestOperation进行AFNetworking 2身份验证

来自分类Dev

使用AFNetworking 1.x进行SSL固定

来自分类Dev

在AFNetworking中使用URL参数和JSON正文进行POST

来自分类Dev

通过AFNetworking使用SDWebImage进行图像加载有很大的优势吗?

来自分类Dev

afnetworking 3.0迁移:如何使用标头和HTTP正文进行POST

来自分类Dev

通过AFNetworking使用SDWebImage进行图像加载有很大的优势吗?

来自分类Dev

使用AFNetworking在目标c中的模型对象内部进行远程数据获取

来自分类Dev

使用AFNetworking保持周期

来自分类Dev

使用AFNetworking解析XML

来自分类Dev

使用AFNetworking设置图像

来自分类Dev

NSURLCredential创建返回null

来自分类Dev

通过Afnetworking进行大图像缓存

来自分类Dev

AFNetworking 3.0迁移以进行重定向块

来自分类Dev

如何通过AFNetworking进行GET请求?

来自分类Dev

通过Afnetworking进行大图像缓存

来自分类Dev

AFNetworking 3.0迁移以进行重定向块

来自分类Dev

允许使用AFNetworking的无效证书

来自分类Dev

使用AFNetworking 2.0上传图像

来自分类Dev

使用AFNetworking上传多张图像

来自分类Dev

如何同步使用AFNetworking 2.0

来自分类Dev

使用AFNetworking 2.0加载图像

来自分类Dev

使用AFNetworking检测超时错误

来自分类Dev

使用AFNetworking 3.0上传图像

来自分类Dev

允许使用AFNetworking的无效证书