Storing secrets
UserDefaults is like a notebook left on the table: fine for settings such as “dark mode on”, but anyone who gets the phone’s backup can read it. The KeychainKeychainThe encrypted store iOS provides for passwords, tokens and keys, private to the app unless shared through an access group.Open in glossary → is a safe built into iOS. It encrypts what you put in it with keys tied to the device and the passcode, and only your app can open its own items.
What goes where:
- Keychain: tokens, passwords, encryption keys, anything that lets someone act as the user.
- UserDefaults: settings and small flags.
- Files: larger data, protected with Data Protection (encrypted while the phone is locked).
The Keychain’s API is old and dictionary-based, so every app wraps it in a small helper like the one below.
Keychain items are encrypted with class keys derived from the device UID and (for most classes) the passcode; the accessibility attribute picks the class. kSecAttrAccessibleWhenUnlocked is the safest default for foreground use; anything read by background work (background refresh, push handling, a background URLSession delegate) needs AfterFirstUnlock, or reads fail with errSecInteractionNotAllowed while the device is locked. The ThisDeviceOnly variants exclude the item from backups and device migration, which is what you want for tokens. Items persist across app deletion (the Keychain isn’t part of the app container), share across your apps and extensions only through an explicit access group, and can require user presence via SecAccessControl (.biometryCurrentSet invalidates the item when Face ID enrollment changes). Files use Data Protection classes (.complete, .completeUnlessOpen, .completeUntilFirstUserAuthentication, the default). And anything compiled into the binary, including obfuscated API keys, should be treated as public: secrets that matter belong on your server.
import Security
struct KeychainError: Error { let status: OSStatus }
enum Keychain {
private static let service = "com.example.bank.auth"
static func save(_ data: Data, for account: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
let attributes: [String: Any] = [
kSecValueData as String: data,
// Readable after the first unlock since boot (needed by background refresh), never backed up
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
]
var status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status == errSecItemNotFound {
status = SecItemAdd(query.merging(attributes) { $1 } as CFDictionary, nil)
}
guard status == errSecSuccess else { throw KeychainError(status: status) }
}
static func read(_ account: String) throws -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecItemNotFound { return nil }
guard status == errSecSuccess else { throw KeychainError(status: status) } // e.g. locked device
return result as? Data
}
static func delete(_ account: String) {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
SecItemDelete(query as CFDictionary)
}
}
// Files: encrypted whenever the device is locked
try data.write(to: url, options: .completeFileProtection)kSecClassGenericPasswordis the item type for passwords and tokens.service+accounttogether are the item’s name, like a label on a drawer.SecItemUpdate, thenSecItemAdd: update the item if it exists, otherwise create it. Adding an item that already exists fails witherrSecDuplicateItem.kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly: readable once the user has unlocked the phone after turning it on, and never copied to backups or a new phone.readthrows for real errors, so a locked device isn’t mistaken for “no token”. Treating every error as “not logged in” is how apps log users out at random.
Tap the line with the bug.
final class AuthStore {
func didLogIn(token: String, refreshToken: String) {
UserDefaults.standard.set(token, forKey: "accessToken")
UserDefaults.standard.set(refreshToken, forKey: "refreshToken")
}
var isLoggedIn: Bool {
UserDefaults.standard.string(forKey: "refreshToken") != nil
}
}Hint: Where does UserDefaults keep its data, and who can read it?
UserDefaults is a plain property list file in the app’s container. It’s included in device backups (unencrypted ones too) and readable on a jailbroken device or with forensic tools. A refresh token there lets anyone with the backup act as the user for weeks.
Store tokens in the Keychain with a ThisDeviceOnly accessibility, and keep only non-secret state (like “has seen onboarding”) in UserDefaults:
func didLogIn(token: String, refreshToken: String) throws {
try Keychain.save(Data(token.utf8), for: "accessToken")
try Keychain.save(Data(refreshToken.utf8), for: "refreshToken")
}Predict the output
A user logs in, deletes the app, and installs it again from the App Store. On first launch the app checks Keychain.read("refreshToken"). What does it find?
The app's container (files, UserDefaults) is deleted with the app, but Keychain items are not. The reinstalled app finds the old token and the user is unexpectedly still logged in, which also matters when a phone changes hands. A common fix: on launch, if a UserDefaults flag like hasLaunchedBefore is missing, this is a fresh install, so delete the Keychain items and then set the flag.
Asking for Face ID before showing something
For sensitive screens (card details, a password vault), ask for Face ID or Touch ID first with LocalAuthentication. Add NSFaceIDUsageDescription to Info.plist, a sentence explaining why.
import LocalAuthentication
func unlockCardDetails() async -> Bool {
let context = LAContext()
var error: NSError?
// .deviceOwnerAuthentication falls back to the passcode if Face ID fails or isn't set up
guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { return false }
do {
return try await context.evaluatePolicy(.deviceOwnerAuthentication,
localizedReason: "Show your card details")
} catch {
return false // the user cancelled or failed
}
}This only asks the user. The card details themselves still come from the server or the Keychain; Face ID is a gate in front of them, not encryption.
Biometrics that actually protect the data
A bare LAContext.evaluatePolicy returns a Bool in your process: on a compromised device it can be hooked to return true. To make biometrics protect the data, put the secret in a Keychain item with an access control; the Secure Enclave then refuses to release it without a successful match:
let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, // removed if the passcode is turned off
.biometryCurrentSet, // invalidated when Face ID enrollment changes
nil
)!
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.bank.vault",
kSecAttrAccount as String: "cardKey",
kSecValueData as String: cardKey,
kSecAttrAccessControl as String: access,
]
SecItemAdd(query as CFDictionary, nil)
// Reading it shows the Face ID prompt; pass an LAContext in kSecUseAuthenticationContext to customize it.For keys that should never leave the hardware at all (signing a login challenge, for example), generate them in the Secure Enclave with CryptoKit’s SecureEnclave.P256.Signing.PrivateKey: the app gets a handle and signatures, never the key bytes.
| Need | Use |
|---|---|
| Tokens used by background work | Keychain, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly |
| Foreground-only secrets | Keychain, WhenUnlocked(ThisDeviceOnly) |
| Data released only after Face ID | Keychain item with SecAccessControl(.biometryCurrentSet) |
| Keys that never leave hardware | CryptoKit SecureEnclave.P256 keys |
| Files | Data Protection: .completeFileProtection where possible |
| Sharing with extensions | Keychain access group + App Group container |
- Keychain survives app deletion: detect a fresh install and wipe.
ThisDeviceOnlykeeps items out of backups and migrations. errSecInteractionNotAllowed= device locked for that class; never treat it as “logged out”.LAContext.evaluatePolicyalone is a UI gate, not protection. Secrets in the binary are public.
Check this part
Where should an app store a refresh token?
The app is deleted and reinstalled. What happens to its Keychain items?
A background refresh reads a token stored with WhenUnlocked while the phone is locked. Result?
What makes Face ID protect data rather than just show a prompt?