tezvyn:

Why store auth tokens in Keychain, not UserDefaults?

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

secure credential storage.

OUTLINE

UserDefaults is an unencrypted plist readable from backups and on jailbroken devices; use Keychain Services, which stores encrypted items with access control; save with SecItemAdd and read with…

WHAT THIS TESTS This confirms you understand the iOS data protection model and will not leak credentials by storing them in plain text. Mishandling tokens is a common, serious mistake, so interviewers probe it directly.

A GOOD ANSWER COVERS UserDefaults is backed by an unencrypted property list file in the app's sandbox. Although the sandbox limits access between apps, the file is plain text, is captured in unencrypted iTunes or local backups, and is trivially readable on a jailbroken device or via backup extraction tools, so storing an auth token there exposes it. The correct tool is Keychain Services, a secure, encrypted store managed by the system. Items are encrypted at rest, scoped to your app or an access group, and tagged with an accessibility class such as kSecAttrAccessibleWhenUnlockedThisDeviceOnly to control when and whether they sync or survive restore. You can further gate access behind Face ID or Touch ID with access control flags. To save, build a query dictionary with kSecClassGenericPassword and the data, then call SecItemAdd. To read, call SecItemCopyMatching with kSecReturnData true. Use SecItemUpdate to change and SecItemDelete to remove.

COMMON WRONG ANSWERS Believing the sandbox encrypts UserDefaults. Suggesting you encrypt the token yourself and store it in UserDefaults, which still leaks the key. Forgetting accessibility classes and biometric protection entirely.

LIKELY FOLLOW-UPS What do the accessibility classes control? How does the Keychain behave across backup and restore? Why is the C API often wrapped in a helper? How do you require biometrics?

ONE CONCRETE EXAMPLE After login, the app stores the bearer token by calling SecItemAdd with kSecClass generic password, the account name, the token data, and accessibility WhenUnlockedThisDeviceOnly so it never syncs or restores to another device. On the next launch SecItemCopyMatching returns the encrypted token for the API client. On logout, SecItemDelete removes it. The same data in UserDefaults would sit readable in the app's plist.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.