skip to content

Keychain Services

Keychain Services stores passwords, tokens and keys through the SecItem API, with LAContext and Face ID held as its access-control clause. Interviewers ask about accessibility and biometry.

on this pageshow

explore

questions

6

With Keychain Services on iOS, how do you save, read and delete a member's refresh token using the SecItem functions?

level: juniorimportance: must knowfreq 75%

answer

  1. one dictionary per call
  2. item class plus identifying attributes
  3. service and account name the item
  4. ask for the data back explicitly
  5. statuses, not throws: errSecItemNotFound

basics

~10 s

Build a dictionary with kSecClass set to kSecClassGenericPassword plus kSecAttrService and kSecAttrAccount, then call SecItemAdd with kSecValueData, SecItemCopyMatching with kSecReturnData, and SecItemDelete; each returns an OSStatus to check.

solid answer

~40 s

Keychain Services is a C API driven by dictionaries. A token is a `kSecClassGenericPassword` item named by `kSecAttrService` (your label for the secret) and `kSecAttrAccount`. To save, call `SecItemAdd` with those keys plus `kSecValueData` holding the token's bytes. To read, pass the same keys plus `kSecReturnData: true` to `SecItemCopyMatching` (one match is the default) and cast the `CFTypeRef` result to `Data`. To sign out, pass the identifying keys to `SecItemDelete`, which removes every matching item. None of these calls throws: each returns an `OSStatus`, so you compare it with `errSecSuccess` and treat `errSecItemNotFound` as "nothing stored". Unlike `UserDefaults`, which writes a plain property list into the app's container, the keychain encrypts the data and releases it only under the item's accessibility class.

code

swift · 28 lines
swift
import Foundation
import Security

func baseQuery() -> [String: Any] {
    [kSecClass as String: kSecClassGenericPassword,
     kSecAttrService as String: "com.example.carshare.auth",
     kSecAttrAccount as String: "refresh-token"]
}

func saveToken(_ token: Data) -> OSStatus {
    var attributes = baseQuery()
    attributes[kSecValueData as String] = token
    return SecItemAdd(attributes as CFDictionary, nil)
}

func readToken() -> Data? {
    var query = baseQuery()
    query[kSecReturnData as String] = true
    query[kSecMatchLimit as String] = kSecMatchLimitOne
    var result: CFTypeRef?
    guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess else { return nil }
    return result as? Data
}

func deleteToken() -> Bool {
    let status = SecItemDelete(baseQuery() as CFDictionary)
    return status == errSecSuccess || status == errSecItemNotFound
}

go deeper

for a junior

Recall the four SecItem calls, the generic password class with service and account, and that results come back as OSStatus codes you must check.

for a middle

Explain how return keys shape the result type, why the default match limit is one, and why a delete or update touches every matching item.

for a senior

Show that status handling drives behaviour: item-not-found means signed out, interaction-not-allowed means try later, and a wrapper that maps both to nil causes false sign-outs.

for a principal

Argue for one keychain wrapper per codebase so every feature uses the same identity keys, explicit accessibility and status mapping, instead of hand-built dictionaries scattered across modules.

## What Keychain Services stores **Keychain Services** is the Security framework's API for small secrets such as passwords, tokens and keys. The system keeps them in an encrypted database called the **keychain**; an app never opens that database itself. Instead it describes what it wants in a dictionary and hands the dictionary to one of four C functions, the **SecItem** calls. Each returns an `OSStatus` code rather than throwing a Swift error, so every caller has to check it. Where a token lives matters. `UserDefaults` writes a property list into the app's container with no encryption of its own. A keychain item's data is encrypted, and it is released only under the item's **accessibility class**, which by default is `kSecAttrAccessibleWhenUnlocked`: readable only while the phone is unlocked. ## The query dictionary Every call takes a dictionary whose keys are Security constants of type `CFString`, so Swift code writes `kSecClass as String`. For a token the keys play four roles: | Role | Key | Value for a refresh token | |---|---|---| | Item class | `kSecClass` | `kSecClassGenericPassword` | | Identity | `kSecAttrService`, `kSecAttrAccount` | `"com.example.carshare.auth"`, `"refresh-token"` | | Secret bytes | `kSecValueData` | the token as `Data` | | What to return | `kSecReturnData`, `kSecReturnAttributes` | `true` on reads | - **`kSecClassGenericPassword`** suits a secret only your app interprets. `kSecClassInternetPassword` adds server-oriented attributes such as `kSecAttrServer`, `kSecAttrProtocol` and `kSecAttrPort`, useful when the secret is a password for one particular server. - **`kSecAttrService` and `kSecAttrAccount`** together name the item. With the access group and the synchronizable flag they form the generic password's primary key, so two items cannot share all four. - **Search keys** such as `kSecMatchLimit` refine a read. `kSecMatchLimitOne` is already the default: a read returns the first match only. ## The four SecItem calls 1. **`SecItemAdd(attributes, result)`** creates an item from the class, the identity keys and `kSecValueData`. Pass `nil` as `result` unless you asked for something back. 2. **`SecItemCopyMatching(query, &result)`** searches. The result's type follows the return keys: `kSecReturnData` alone gives `Data`, several return keys give a dictionary, and no return key gives no result at all. 3. **`SecItemUpdate(query, attributesToUpdate)`** finds the matching items and changes them, for example writing a new `kSecValueData` after the token rotates. It changes every item the query matches. 4. **`SecItemDelete(query)`** removes every matching item by default; it is the sign-out call. ## Reading the result safely `SecItemCopyMatching` writes into an `inout` `CFTypeRef?`. With `kSecReturnData` and a single match, cast it with `as? Data`. Ask for `kSecReturnAttributes` as well and the result becomes a dictionary that holds the bytes under `kSecValueData`, so the cast must change with it. Leaving out every return key is a classic bug: on iOS such a query returns no result, so the token variable stays `nil` even though the item exists. ## Checking OSStatus - **`errSecSuccess`** (0): the call did what was asked. - **`errSecItemNotFound`** (-25300): nothing matched. On a read this usually means the member never signed in on this install; on a delete it can count as success, because the goal "no token stored" already holds. - **`errSecDuplicateItem`** (-25299): `SecItemAdd` met an item with the same primary key, so a save that runs twice must update instead of adding. - **`errSecInteractionNotAllowed`** (-25308): the item exists but its data is unavailable right now, for example while the phone is locked. - **`SecCopyErrorMessageString(status, nil)`**, available since iOS 11.3, turns any status into readable text for a log line. ## Mistakes that show up in review - Treating every non-success status as "signed out", which logs a member out whenever a read happens on a locked phone. - Building a delete query from `kSecClass` alone, which removes every generic password the app can reach, including ones other features own. - Converting the bytes with `String(data:encoding:)` and force-unwrapping, instead of keeping `Data` until the token is actually needed. - Calling the read on the main thread for an item guarded by Face ID; a plain item returns quickly, but an access-controlled read waits for the prompt and belongs on a background thread. - Storing the token in `UserDefaults` "for now" and planning to move it later; the plain copy stays in the container until something deletes it.

  • With Keychain Services, what does SecItemCopyMatching hand back when the query has no return key such as kSecReturnData?
    No result. On iOS a query without a return-type key returns nothing through the result parameter, so the variable stays `nil` even when the item exists. Add `kSecReturnData` for the bytes, `kSecReturnAttributes` for the attributes, or both, in which case the result is a dictionary with the bytes under `kSecValueData`.
  • When would you store a secret as kSecClassInternetPassword rather than kSecClassGenericPassword?
    When it is a password for a specific server and you want the keychain to record `kSecAttrServer`, `kSecAttrProtocol`, `kSecAttrPort` and `kSecAttrPath`, which are also part of its primary key. A token only your app interprets needs none of those, so a generic password named by `kSecAttrService` and `kSecAttrAccount` is the usual choice.
  • Why should the SecItemDelete query used at sign-out name the service and account?
    `SecItemDelete` removes every item that matches, across all of the app's access groups. A dictionary holding only `kSecClass` would wipe every generic password the app can reach, including items other features or a shared extension depend on. Name `kSecAttrService` and `kSecAttrAccount`, and accept `errSecItemNotFound` as success.

  • The SecItem functions throw Swift errors that you catch with do and try.
  • A read without kSecReturnData still hands back the stored token.
  • SecItemDelete removes only the first item that matches the query.
  • Every token sent to a server must use kSecClassInternetPassword.
  • UserDefaults is as safe as the keychain because the app sandbox protects it.
open as a page

With Keychain Services, why does SecItemAdd return errSecDuplicateItem when an app saves a refreshed token, and how should the save be written?

level: middleimportance: must knowfreq 60%

basics

~20 s

A generic password with the same kSecAttrService, kSecAttrAccount, access group and synchronizable flag already exists, so SecItemAdd refuses a second one. Write the save as SecItemUpdate with the new kSecValueData, calling SecItemAdd only when the update returns errSecItemNotFound.

open as a page

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?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Store 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.

open as a page

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?

level: seniorimportance: must knowfreq 55%

basics

~20 s

The 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.

open as a page

With Keychain Services, how does a car-sharing app share its digital-key secret with its widget extension, and what breaks when the access group is wrong?

level: middleimportance: should knowfreq 35%

basics

~20 s

Give the app and the widget extension the same Team ID-prefixed keychain-access-groups entry, and add and query the item with kSecAttrAccessGroup set to it. Otherwise the item lands in the app's private group and the widget gets errSecItemNotFound.

open as a page

As iOS lead, what Keychain Services standard would you set for each secret's accessibility class, iCloud sync, access group and biometric flag, and how should the app handle reinstall?

level: principalimportance: should knowfreq 30%

basics

~20 s

Fix four choices per secret in one wrapper: an explicit kSecAttrAccessible class, sync only for user-visible passwords, a named access group only where an extension needs it, and biometryCurrentSet only for high-value secrets. Detect reinstall leftovers with a first-launch marker.

open as a page