Storing authentication tokens in iOS - NSUserDefaults vs Keychain?

What is the place where I should store tokens when a user logs in? I do not save passwords (obviously where I use Keychain), but only a token. Many places say they simply use NSUserDefaults, but some people from StackOverflow are really very interested in Keychain.

Is NSUserDefaults accurate?

+61
api ios objective-c keychain nsuserdefaults
May 28 '13 at 15:10
source share
3 answers

I highly recommend you use a keychain - this is exactly what Facebook does to store its session tokens.

NSUserDefaults not secure or encrypted - it is easy to open and read both on the device and when syncing with a Mac. Thus, although user defaults are a good place for things like settings and configuration information, they are not a good place for anything sensitive, such as passwords.

Session tokens should almost always be processed in the same way as passwords, so they should be stored securely in the keychain, where they will be encrypted. Apple has some sample code ( GenericKeychain ) that shows the basic implementation, and you will find other examples by searching StackOverflow. Hope this helps you.

+86
May 28 '13 at 15:18
source share

Worth a look at Lockbox . It really makes it easy to interact with Keychain.

+20
May 28 '13 at 15:24
source share

NSUserDefaults can be used without problems. Please check the documentation https://developer.apple.com/documentation/security/keychain_services

Keychain services are designed for "secrets" that the user clearly cares about, that is, passwords, private keys, or even secured notes, i.e. But access tokens are temporary hashes generated after a password is entered by the user, and have a limited time. And even in the event of theft, an attacker will not be able to completely steal an account - the owner can log in to another device and the previous access token will be reset. Thus, formally there is no ban on storing access tokens in UserDefaults.

Data from UserDefaults can only be stolen if the device itself is stolen, but I think the level of content security is much lower than the physical device itself. I think that the user will not worry about the token in this case, but about the device.

Nevertheless, it is recommended to store it in a keychain, but this is just excessive (!) Use of security, which is usually recommended to casual users on the Internet and is not required by Apple. There is no documentation from Apple, it says that tokens should be stored in a keychain (if you can find one, then please comment on one below).

So the answer is you can use both. However, if your application works with content that is expensive compared to a stolen iPhone, it is better to use Keychain, but this is just a recommendation.

+2
Jan 16 '19 at 8:40
source share



All Articles