With Keychain Services, how do you require Face ID before a car-sharing app reads its digital-key secret, and why does the read fail after the member re-enrols Face ID?
answer
- the keychain enforces the check itself
- SecAccessControlCreateWithFlags with a flag
- an LAContext passed with the query
- biometryCurrentSet versus biometryAny
- invalidated item, not a cancelled prompt
basics
~20 sStore the secret with a SecAccessControl built by SecAccessControlCreateWithFlags using .biometryCurrentSet, and read it with an LAContext under kSecUseAuthenticationContext. Re-enrolling Face ID invalidates such an item, so the app must delete it and re-provision after sign-in.
solid answer
~40 sBuild the item's access control with `SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, .biometryCurrentSet, &error)` and add it under `kSecAttrAccessControl`; the keychain then releases the data only after Face ID succeeds, so no code path can skip the check. To read, pass an `LAContext` with its `localizedReason` set under `kSecUseAuthenticationContext` to `SecItemCopyMatching`, off the main thread because the call waits for the prompt, and add `NSFaceIDUsageDescription` to Info.plist. `.biometryCurrentSet` ties the item to the enrolled set: when Face ID is re-enrolled, or Touch ID fingers change, the item is invalidated and no authentication brings it back. Treat that failure as "key gone": delete the item, send the member through sign-in and store a fresh secret. `.biometryAny` or `.userPresence` survive re-enrolment, trading that protection for fewer forced sign-ins.
code
swift · 21 linesimport Foundation
import Security
func storeCarKey(_ secret: Data) -> OSStatus {
var error: Unmanaged<CFError>?
guard let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.biometryCurrentSet,
&error
) else { return errSecParam }
let attributes: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.carshare.car-key",
kSecAttrAccount as String: "unlock-secret",
kSecAttrAccessControl as String: access,
kSecValueData as String: secret
]
return SecItemAdd(attributes as CFDictionary, nil)
}go deeper
Recall that a keychain item can require Face ID through an access control object, and that Info.plist needs NSFaceIDUsageDescription.
Explain SecAccessControlCreateWithFlags with its protection and flags, how an LAContext under kSecUseAuthenticationContext drives the prompt, and why the read runs off the main thread.
Diagnose reads that fail after re-enrolment: an invalidated biometryCurrentSet item, told apart from a cancelled prompt, then deleted and re-provisioned after sign-in.
Decide which secrets justify biometryCurrentSet and its forced sign-ins, which can use biometryAny or userPresence, and how support handles members locked out by re-enrolment.
## Two dimensions on one item A keychain item can carry a **`SecAccessControl`** object under `kSecAttrAccessControl`. `SecAccessControlCreateWithFlags(allocator, protection, flags, error)` builds it from two inputs: a **protection** value, one of the `kSecAttrAccessible` constants deciding in which lock state the data can be decrypted, and **flags** from `SecAccessControlCreateFlags`, deciding which user authentication must succeed before each use. Because the protection travels inside the access control, the add dictionary does not set `kSecAttrAccessible` separately. ## Choosing the flag | Flag | What it requires | After a new face or finger is enrolled | |---|---|---| | `.biometryCurrentSet` | Face ID or Touch ID from the currently enrolled set | The item is invalidated | | `.biometryAny` | Face ID or Touch ID, any enrolment | The item stays readable | | `.userPresence` | Biometry or the device passcode; biometry need not be enrolled | The item stays readable | | `.devicePasscode` | The device passcode | Not affected | `.biometryCurrentSet` and `.biometryAny` exist since iOS 11.3; the older `touchIDCurrentSet` and `touchIDAny` names are deprecated in their favour. Flags combine with `.or` and `.and` when an item needs more than one constraint. ## Storing and reading the digital-key secret 1. Create the access control with `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` and `.biometryCurrentSet`. That class refuses to store the item on a phone without a passcode, deletes it if the passcode is later removed, and never migrates it to another device. 2. Add the item with `kSecAttrAccessControl` and `kSecValueData`, using the update-or-add pattern for later changes. 3. To read, create an `LAContext`, set its `localizedReason`, and pass it under `kSecUseAuthenticationContext` in the `SecItemCopyMatching` query. Keychain Services asks LocalAuthentication to authenticate; the match itself happens in the Secure Enclave, and only a pass or fail reaches the keychain. 4. Run the read **off the main thread**: Apple's documentation warns that access-controlled reads can block while the prompt is on screen. 5. Add **`NSFaceIDUsageDescription`** to Info.plist. Without it the system won't let the app use Face ID; Touch ID needs no such string. Compared with calling `evaluatePolicy` and then reading a plain item, the keychain itself withholds the data until authentication succeeds, so a code path that skips the check simply gets nothing. ## Why the read fails after re-enrolment With `.biometryCurrentSet`, the Security header states that when Face ID is re-enrolled, or Touch ID fingers are added or removed, **the item is invalidated**. No later authentication unlocks it. That is the point of the flag: someone who learns the passcode cannot enrol their own face and then open the car. The app should: - treat a failed read of that item, other than the member cancelling the prompt, as "the key is gone"; - delete the stale item with `SecItemDelete`; - send the member through sign-in and fetch a fresh secret from the server, then store it under a new access control. Choose `.biometryAny` or `.userPresence` instead when re-enrolment should not cost a sign-in; that trades the protection above for fewer support requests. ## Lockout and the passcode path LocalAuthentication locks biometry after five failed attempts, and the user then has to enter the device passcode, preferably at the Lock Screen, before Face ID works again. An item protected by `.biometryCurrentSet` alone offers no passcode route of its own, so during a lockout the car cannot be opened from the app until the member unlocks biometry with the passcode, at the Lock Screen or in the app through `.deviceOwnerAuthentication`. Two design choices, each with a cost: - Combine flags, for example `[.biometryCurrentSet, .or, .devicePasscode]`, so the passcode also satisfies the item; anyone who knows the passcode can then read it. - Keep the strict flag and offer a server-side recovery path, such as signing in again to receive a new secret. ## LAContext details worth knowing - **Reusing a context.** If the context passed under `kSecUseAuthenticationContext` has already authenticated, the read succeeds without prompting again. Without the key, each call creates a single-use context. - **No UI allowed.** With `interactionNotAllowed` set to true, a read that would prompt fails with `errSecInteractionNotAllowed` instead. - **Wording the UI.** `biometryType` reports `.faceID` or `.touchID`, but only after `canEvaluatePolicy(_:error:)` has run on that context. - **Spotting enrolment changes early.** On iOS 18 and later, `domainState.biometry.stateHash` changes when the enrolled set changes; `evaluatedPolicyDomainState` is deprecated since iOS 18 in its favour. - **The prompt string.** `kSecUseOperationPrompt` is deprecated since iOS 14; set `localizedReason` on the context instead.
- With Keychain Services, why does the add dictionary for the digital key set kSecAttrAccessControl but not kSecAttrAccessible?`SecAccessControlCreateWithFlags` already takes the protection class as its second argument, so the access control object carries both the lock-state rule and the authentication flag. Apple's guide notes you don't need to set the accessible attribute directly when it is part of the access control; setting both only invites the two to disagree.
- How can an iOS 18 app notice that the enrolled faces changed before it tries to read the protected item?After a successful biometric evaluation, store `domainState.biometry.stateHash` from the `LAContext`; when a later value differs, the enrolled set changed. `evaluatedPolicyDomainState` served this purpose before and is deprecated since iOS 18. The value can also change across major OS versions with no enrolment change, so treat it as a hint for the UI; the invalidated item is the real enforcement.
- The member taps Cancel on the Face ID prompt during the read; should the app delete the digital-key item?No. A cancelled prompt says nothing about the item; it is still valid and the next read can succeed. Distinguish cancellation from an invalidated item, and delete and re-provision only in the second case, otherwise a single cancel forces a full sign-in.
- biometryCurrentSet and biometryAny behave the same once Face ID is set up.
- After re-enrolment the old item reads again once the new face authenticates.
- kSecUseOperationPrompt is still the way to set the Face ID prompt text.
- Touch ID devices also need NSFaceIDUsageDescription in Info.plist.
- A keychain read protected by Face ID is fine to call on the main thread.