With Keychain Services on iOS, how do you save, read and delete a member's refresh token using the SecItem functions?
answer
- one dictionary per call
- item class plus identifying attributes
- service and account name the item
- ask for the data back explicitly
- statuses, not throws: errSecItemNotFound
basics
~10 sBuild 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 sKeychain 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 linesimport 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
Recall the four SecItem calls, the generic password class with service and account, and that results come back as OSStatus codes you must check.
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.
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.
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.