Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c clear NSURLCredential - NSURLCredentialPersistenceForSession

I am using NSURLCredentials in this method:

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

And now I am looking to clear the NSURLCredentials in a logout method like so:

-(void)logout
{
   //Clear NSURLCredentialPersistenceForSession
}

How would I go about doing this? Should I reset the NSURLCredentials or is there away to clear them ?

UPDATE

I found this solution:

NSURLCredentialStorage *credentialStorage = [NSURLCredentialStorage sharedCredentialStorage];
    NSDictionary *credentialsDicationary = [credentialStorage allCredentials];


    for (NSURLProtectionSpace *space in [credentialsDicationary allKeys]) {

        NSDictionary *spaceDictionary = [credentialsDicationary objectForKey:space];

        for (id userName in [spaceDictionary allKeys]) {

            NSURLCredential *credential = [spaceDictionary objectForKey:userName];

            [credentialStorage removeCredential:credential forProtectionSpace:space];

        }

    }

From here: Using NSURLCredentialPersistenceForSession while request and then clearing the credentials on logout still persist the cerdentials

Is this the best way? I only have 1 credential stored. Also this code gives me a warning on this line:

NSURLCredential *credential = [spaceDictionary objectForKey:userName];

and here is the warning...how do I remove this warning?

/Users/jsuske/Documents/SSiPad(Device Only)ios7/SchedulingiPadApplication/ViewControllers/LHLoginController.m:496:73: Local declaration of 'userName' hides instance variable

UPDATE

Okay, so I have 3 methods:UserLogin, Login and LogoutButtonPressed

UserLogin: I am using AFNetworking to connect to a Windows Authenticated URL using NSURLCredential as shown above:

-(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];

}

This method is being called by the Login method:

- (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;

        }
    }];

}

And I am trying to clear my session with the 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];
            }
        }
    }
}

I got this code from this example: http://www.springenwerk.com/2008/11/i-am-currently-building-iphone.html

Now my problem I am having is that when I trigger the logout button and then goto trigger the login method WITH NO CREDENTIALS I can still login, If I logout then wait 2 - 3 minutes and login with NO CREDENTIALS I can't login. Why is it behaving this way, its almost like the creds are still saved. Please help.

UPDATE

I have tried to clear the cache, cookies and creds inside my LogoutButtonPressed:

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

and it still did not work.

like image 346
user979331 Avatar asked Apr 09 '15 19:04

user979331


1 Answers

This issue can be fixed easily by adding a random number to the end of the 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];

}

And make sure you have a random number at the end of all URLs you are calling.

like image 148
user979331 Avatar answered Oct 06 '22 08:10

user979331