Storing secrets in the Keychain

Persistence Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Fill the blank

The token is only used while the app is open and must not move to another device. Fill the blank.

let query: [String: Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrService as String: "com.example.auth",
    kSecAttrAccount as String: "accessToken",
    kSecValueData as String: Data(token.utf8),
    kSecAttrAccessible as String: ____
]
let status = SecItemAdd(query as CFDictionary, nil)
Options
Hint 1 of 1

Two requirements: when unlocked, and this device only.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A kSecAttrAccessibleWhenUnlockedThisDeviceOnly

Correct. It's readable only while unlocked and never migrates.

Why not the others?
  • B kSecAttrAccessibleAfterFirstUnlock. It stays readable while locked and can move to a new device through a backup.
  • C kSecAttrAccessibleAlways. It's deprecated and readable even when locked.
  • D kSecClassInternetPassword. That is an item class, not an accessibility value.

30-second answer

Use the Security framework's SecItemAdd, SecItemCopyMatching, SecItemUpdate and SecItemDelete with a generic-password item identified by service and account. Choose the accessibility class deliberately: kSecAttrAccessibleWhenUnlockedThisDeviceOnly keeps a token readable only while unlocked and stops it moving to another device. Wrap the calls in a small typed store.

Practise saying it · 45 s. No recording, just a timer

Explain how you store a token securely.

Say your answer out loud, then check which of these points you covered:

  • SecItem APIs
  • Accessibility class
  • Handle OSStatus
  • Typed wrapper

Deep dive

errSecDuplicateItem means you should update instead of add.

Use AfterFirstUnlock if background tasks must read the item.

Access groups share items with extensions.

Add kSecAttrAccessControl with biometry to require Face ID for reading.

Common mistakes

  • Ignoring OSStatus results.
  • Using an accessibility class that is too permissive.

Senior take & follow-ups

Seniors pick the accessibility class by when the item is needed and whether it may migrate.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you require Face ID to read an item?

    Show hint

    SecAccessControl with .biometryCurrentSet.

  2. What does ThisDeviceOnly change?

    Show hint

    The item isn't restored to another device from a backup.

Suggest a fix if something here is wrong or out of date.