Last Updated: July 25, 2019
·
25.78K
· autresphere

Storing password in keychain the smart way

NSURLCredential is the perfect class to store username and password in the keychain. No need to bother with NSUserDefaults nor any keychain wrapper.

Once the user is logged in, you can store his username and password to the keychain:

NSURLCredential *credential;

credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:self.loginProtectionSpace];

As stated in Apple Doc, NSURLCredentialPersistencePermanent must be used to store in the keychain.

Then, each time the app is launched, you can check whether your user was already logged in by searching for any credential in order to automatically log back your user (if need be):

NSURLCredential *credential;
NSDictionary *credentials;

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
NSLog(@"User %@ already connected with password %@", credential.user, credential.password);

You also need to clean the credential when the user wants to log out:

NSURLCredential *credential;
NSDictionary *credentials;

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:obj forProtectionSpace:self.loginProtectionSpace];

loginProtectionSpace is created once for all.

Please, note this sample code assumes there is only one credential in this space, which is usually the case unless you manage several accounts.

3 Responses
Add your response

Hi Philip,

Can you also post a sample concerning the self.loginProtectionSpace? I'm a bit lost on how to go about it.

Best,
Sidney

over 1 year ago ·

Hi Sidney,

You can create an NSURLProtectionSpace like that:
NSURL *url = [NSURL URLWithString:@"http://www.example.com"];
protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url.host
port:[url.port integerValue]
protocol:url.scheme
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPDigest];

Please have a look at a more detailed explanation on http://stackoverflow.com/questions/8565087/afnetworking-and-cookies/17997943#17997943

Phil

over 1 year ago ·

Great stuff! Thanks for this,

Sidney

over 1 year ago ·