6

My app (like most) is going to be leveraging many remote services... so when a user authenticates themselves, I need to store their username and password (or some kind of flag) so that they don't have to authenticate all over the app.

Where is the best/quickest/easiest place to store this user data?

demongolem
  • 9,474
  • 36
  • 90
  • 105
dcolumbus
  • 9,596
  • 26
  • 100
  • 165

3 Answers3

11

You can still store the username and server URL with NSUserDefaults, but Keychain services is the best idea if you're storing a password. It's part of the C-Based security framework, and there'a a great wrapper class SFHFKeychainUtils, to give it an Objective-C API.

To save:

NSString *username = @"myname";
NSString *password = @"mypassword";
NSURL *serverURL = [NSURL URLWithString:@"http://www.google.com"];

[SFHFKeychainUtils storeUsername:username andPassword:password forServiceName:[serverURL absoluteString] updateExisting:YES error:&error]

To restore:

NSString *passwordFromKeychain = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:[serverURL absoluteString] error:&error];
Leehro
  • 561
  • 5
  • 10
  • I have a project that shares a common library between OSX and iOS. My login management is mostly contained in that shared library. I removed #import from the header file, and this compiles fine for both OSX and iOS. **I haven't tested the OSX client yet. +1 for reusable code. – Brad G Jun 07 '13 at 10:11
8

NSUserDefaults

Save like this:

[[NSUserDefaults standardUserDefaults] setObject:username    forKey:@"username"];
[[NSUserDefaults standardUserDefaults] setObject:password forKey:@"password"];
[[NSUserDefaults standardUserDefaults] synchronize];

Fetch like this:

    NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
    NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];
Rayfleck
  • 12,116
  • 8
  • 48
  • 74
5

Storing secure data in an insecure file (user defaults) isn't usually a good idea. Look into Keychain Services, which encrypts sensitive login information and such.

http://developer.apple.com/library/mac/#documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html

sudo rm -rf
  • 29,408
  • 19
  • 102
  • 161
  • I just read up on this in the Help and it looks like what I need! I'm assuming that along with a password, you can also store other kinds of information within the keychain? – dcolumbus May 12 '11 at 00:48
  • I haven't used it much myself, so I can't give a definitive answer, but I'm pretty sure you can store some user information along with the authentication data. If you're looking for an example, [check out the sample project from the documentation here](http://developer.apple.com/library/ios/#samplecode/GenericKeychain/Introduction/Intro.html). – sudo rm -rf May 12 '11 at 01:05