With Keychain Services, why does a car-sharing app's background token refresh get errSecInteractionNotAllowed while the phone is locked or freshly rebooted, and how do you fix it?
answer
- data protection follows the lock state
- the default class is when-unlocked
- nothing readable before the first unlock
- AfterFirstUnlockThisDeviceOnly for background reads
- a transient status, never a sign-out
basics
~20 sThe token has the default kSecAttrAccessibleWhenUnlocked class, so a locked phone yields errSecInteractionNotAllowed. Store it as kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly and treat the status as retry later: before the first unlock after a reboot, no supported class is readable.
solid answer
~40 sAn item added without `kSecAttrAccessible` gets `kSecAttrAccessibleWhenUnlocked`, so its data is sealed whenever the phone is locked, and `SecItemCopyMatching` returns `errSecInteractionNotAllowed` (-25308) to a background task. Fix it in three parts. First, store the refresh token with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, the class the header recommends for items background apps need. Second, migrate items already stored: accessibility is not part of the primary key, so re-adding returns `errSecDuplicateItem`; use `SecItemUpdate` with the new class instead. Third, handle the status as transient: until the first unlock after a reboot, only the `Always` classes, deprecated since iOS 12, are readable, so reschedule the refresh and never delete the token or sign the member out. Keep the sign-out path for `errSecItemNotFound`.
code
swift · 31 linesimport Foundation
import Security
enum TokenRead {
case token(Data)
case notStored
case lockedTryLater
case failed(OSStatus)
}
func readRefreshToken() -> TokenRead {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.carshare.auth",
kSecAttrAccount as String: "refresh-token",
kSecReturnData as String: true
]
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
switch status {
case errSecSuccess:
guard let data = result as? Data else { return .failed(status) }
return .token(data)
case errSecItemNotFound:
return .notStored // genuinely signed out
case errSecInteractionNotAllowed:
return .lockedTryLater // data sealed by lock state: reschedule, keep the item
default:
return .failed(status)
}
}go deeper
Recall that keychain items have an accessibility class, that the default is readable only while unlocked, and that a locked phone returns errSecInteractionNotAllowed.
Explain each kSecAttrAccessible value: when-unlocked versus after-first-unlock, what ThisDeviceOnly changes for backups, and why the Always pair is deprecated.
Diagnose the field report: default class on the token, a wrapper that maps every status to signed out, the reboot window, and the migration via SecItemUpdate.
Weigh background availability against exposure for each secret, and require explicit classes, status mapping and locked-device tests in the team's keychain code.
## What the status means `errSecInteractionNotAllowed` (-25308) is the Security framework's "not now". For a plain item, the header's section on accessibility values states the case: when `SecItemCopyMatching` is asked for an item's data and that data is not available until the device is unlocked, it returns this status. The item exists; its **accessibility class** keeps the data sealed in the current lock state. ## Why the background refresh hits it An item added without `kSecAttrAccessible` gets the default class, `kSecAttrAccessibleWhenUnlocked`: readable only while the phone is unlocked. A refresh that runs from a background task while the phone sits locked in a pocket therefore fails, even though the same code works every time a tester runs it with the app open. After a reboot it is stricter still: until the user unlocks once, after-first-unlock items stay sealed too. | `kSecAttrAccessible` value | Readable | Migrates to a new device in an encrypted backup | |---|---|---| | `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` | While unlocked, and only with a passcode set | No | | `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` | While unlocked | No | | `kSecAttrAccessibleWhenUnlocked` (default) | While unlocked | Yes | | `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` | After the first unlock since restart | No | | `kSecAttrAccessibleAfterFirstUnlock` | After the first unlock since restart | Yes | | `kSecAttrAccessibleAlways` and `...AlwaysThisDeviceOnly` | Any time; deprecated since iOS 12 | Only the first | ## The fix, in three parts 1. **Store the token with an after-first-unlock class.** `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` is what the header recommends for items background applications need, and the `ThisDeviceOnly` suffix keeps the token from moving to another phone restored from a backup. 2. **Migrate items already stored.** Accessibility is not part of the item's primary key, so adding again with the new class returns `errSecDuplicateItem`. Call `SecItemUpdate` with the new `kSecAttrAccessible` in the attributes to update, or delete and re-add, once, while the app is in the foreground and the phone is unlocked. 3. **Treat the status as transient.** Before the first unlock nothing but the deprecated `Always` pair is readable, so no class choice removes the case. Map `errSecInteractionNotAllowed` to "try later", reschedule the refresh, and never delete the token or sign the member out because of it. Reserve the sign-out path for `errSecItemNotFound`. ## The same status from a different cause The status also appears when an item needs **user authentication** that cannot be shown. A Face ID-protected item read with an `LAContext` whose `interactionNotAllowed` is true fails with `errSecInteractionNotAllowed` instead of prompting; the older `kSecUseAuthenticationUIFail` value, deprecated since iOS 14, did the same. When a background task reports the status, check which item it read: a lock-state problem is solved by the class, an authentication problem by not reading that item in the background at all. ## Diagnosing it in the field - Log the raw `OSStatus` with the item's service name, never the data, so -25308 is distinguishable from -25300 in a field report. - Reproduce on a device: lock the phone and trigger the background task, then repeat right after a reboot, before unlocking. - Check every target that writes the item; an extension that saves the token with its own dictionary may still rely on the default class. - Review the wrapper's error mapping: one that turns any non-zero status into `nil` makes "locked" look exactly like "signed out". ## Retrying at the right moment Rescheduling blindly can burn the background task's budget on another sealed read. The app can ask UIKit first: `UIApplication.shared.isProtectedDataAvailable` is false while the phone's protected data is locked, and `UIApplication.protectedDataDidBecomeAvailableNotification` (with the delegate's `applicationProtectedDataDidBecomeAvailable(_:)`) fires when it unlocks, a natural point to retry a refresh that had to wait. These signals describe the lock state; the keychain's own answer is still the status code, so the read must keep its `errSecInteractionNotAllowed` branch. ## Why ThisDeviceOnly here `kSecAttrAccessibleAfterFirstUnlock` would also fix the background read, but its items migrate to a new device when an encrypted backup is restored there. A refresh token tied to one device's session is better kept on that device, so the suffix is the usual choice; the cost is that a member who restores onto a new phone signs in again. Note too that `ThisDeviceOnly` classes cannot be combined with `kSecAttrSynchronizable`, so the token also stays out of iCloud Keychain.
- Would switching the token to kSecAttrAccessibleAfterFirstUnlock alone stop every errSecInteractionNotAllowed in background refresh?No. After a reboot, until the user unlocks once, after-first-unlock items are sealed as well, and only the deprecated `Always` classes are readable then. The class fixes refreshes on a locked phone that has been unlocked since boot; the code must still treat the status as transient and reschedule.
- A background read of a Face ID-protected item also returns errSecInteractionNotAllowed; is the fix the same?No. There the data is gated by an authentication requirement, and a context with `interactionNotAllowed` set fails instead of showing the prompt. No accessibility class changes that. Keep the background refresh on an item without an access-control flag, and read the biometric item only in the foreground.
- Why run the migration to the new accessibility class only while the app is in the foreground?The old items still carry `kSecAttrAccessibleWhenUnlocked`, so touching them from a background launch on a locked phone can meet the same sealed state. Running the `SecItemUpdate` when the app is active and the phone unlocked makes the one-time move reliable.
The accessibility class works like a time-locked shop safe: an after-first-unlock safe stays open all day once the manager opens it in the morning, a when-unlocked drawer locks every time the manager steps out, and before the first morning opening neither of them opens.
- errSecInteractionNotAllowed means the token was deleted, so the member must sign in again.
- kSecAttrAccessibleAfterFirstUnlock makes the item readable right after a reboot.
- Adding the token again with a new class replaces the old item's class.
- kSecAttrAccessibleAlways is the right fix for background reads.
- If it works in the Simulator with the app open, background refresh is covered.