Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 46 ยท Data, Networking and Persistence

Keychain, Biometrics and App Security

Store passwords and tokens in the Keychain, add Face ID or Touch ID with LocalAuthentication, and avoid common security mistakes: embedded secrets, ATS and privacy manifests.

Some data must not be treated like a preference. A password, a login token or a private key is valuable to an attacker, and a mistake can hurt your users. iOS gives you a purpose-built place to keep such secrets, the Keychain, and a way to ask the person in front of the phone to prove who they are, LocalAuthentication (Face ID, Touch ID and the device passcode).

This lesson explains what the Keychain is and how its four calls work, how biometric checks actually fit into a login flow, and which security habits matter most for an ordinary app. It continues the persistence chapter after UserDefaults and files, where we warned against putting secrets there. The Keychain and Face ID are not available on this site, so the framework code is read-only, and the runnable examples are stand-ins that model the rules of the API.

What the Keychain is

The Keychain is an encrypted database managed by the operating system. Your app asks it to store small secret items, usually under a service name and an account name, and asks it again later to hand them back. Compared with a file or UserDefaults it gives you:

  • Encryption handled by the system, with keys protected by the device hardware.
  • Control over when an item is readable, for example only while the device is unlocked.
  • Items that can survive app updates, and in some cases even deleting and reinstalling the app, so do not assume a fresh install starts empty.
  • Optional sharing, between your own apps (keychain access groups) or across the user's devices (iCloud Keychain).

It is meant for small values: passwords, tokens, encryption keys. It is not for big files or lists.

Where should a secret live?

Keychain Passwords, tokens, keys.
UserDefaults Never for secrets.
Source code Anyone can extract it.
Your server Keep real secrets there.

A secret shipped inside the app is not a secret.

1 / 2

The four Keychain calls

The Keychain API is written in C style: you build a dictionary describing the item you want, pass it to a function, and get back a numeric status. Here is how saving a token looks.

Swift
import Security

func saveToken(_ token: String, account: String) throws {
    let data = Data(token.utf8)

    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.myapp",
        kSecAttrAccount as String: account,
        kSecValueData as String: data,
        kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
    ]

    let status = SecItemAdd(query as CFDictionary, nil)
    if status == errSecDuplicateItem {
        let find: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: "com.example.myapp",
            kSecAttrAccount as String: account,
        ]
        let update = [kSecValueData as String: data]
        let updateStatus = SecItemUpdate(find as CFDictionary, update as CFDictionary)
        guard updateStatus == errSecSuccess else { throw KeychainError(status: updateStatus) }
    } else if status != errSecSuccess {
        throw KeychainError(status: status)
    }
}

This is a read-only sketch of the real API. Reading is the same idea in reverse: describe the item, ask for the data and require exactly one match.

Swift
func readToken(account: String) throws -> String? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.myapp",
        kSecAttrAccount as String: account,
        kSecReturnData as String: true,
        kSecMatchLimit as String: kSecMatchLimitOne,
    ]

    var result: AnyObject?
    let status = SecItemCopyMatching(query as CFDictionary, &result)

    if status == errSecItemNotFound { return nil }
    guard status == errSecSuccess, let data = result as? Data else {
        throw KeychainError(status: status)
    }
    return String(decoding: data, as: UTF8.self)
}

A few ideas to hold on to:

  • An item is identified by its class and key attributes. For a generic password that means the service plus the account. Adding the same pair twice returns errSecDuplicateItem (status -25299), which is why a "save" function adds first and updates on duplicate, or deletes then adds.
  • A missing item is errSecItemNotFound (-25300). That is a normal result, not a crash, so map it to nil.
  • kSecAttrAccessible decides when the data can be read. WhenUnlocked means only while the device is unlocked. AfterFirstUnlock also allows background work after the first unlock following a restart. The ThisDeviceOnly variants keep the item out of backups and device transfers. Pick the strictest setting your feature can live with.
  • Always check the status. Never assume a call worked.

A stand-in that follows the rules

Because there is no Keychain here, the next program implements a small look-alike with the same identity rules and the same status codes. It will not protect anything. Its job is to let you rehearse the add, read, update and delete logic, including the duplicate and missing-item cases.

Swift A mini Keychain with real status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In the real API you would wrap these four calls in one small type with save, read and delete methods, so no other code touches Sec functions. That also keeps secrets out of the rest of your code, and makes it easy to swap in a fake during tests (see the environment and dependency injection).

Face ID and Touch ID with LocalAuthentication

The LocalAuthentication framework lets your app ask the system to verify the user. You never see a fingerprint or a face. The system shows its own prompt and gives you back only success or an error.

Swift
import LocalAuthentication

func unlockWithBiometrics() async -> Bool {
    let context = LAContext()
    var error: NSError?

    guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
        return false   // no biometrics, not enrolled, or locked out
    }

    do {
        return try await context.evaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics,
            localizedReason: "Unlock your notes"
        )
    } catch {
        return false
    }
}

Things to know:

  • Add NSFaceIDUsageDescription to Info.plist, a sentence explaining why you use Face ID. Without it, Face ID requests fail on devices that have it.
  • Two common policies. .deviceOwnerAuthenticationWithBiometrics accepts only Face ID or Touch ID. .deviceOwnerAuthentication also allows the device passcode as a fallback, which is usually friendlier.
  • Check availability before showing a button. Biometrics can be unavailable (older device), not enrolled, or locked after too many failures (LAError.biometryLockout).
  • Handle every outcome. The user may cancel, choose "Enter Password" (userFallback), or fail to match.

A biometric check is a gate, not a lock

A boolean true from evaluatePolicy only says "the system believes the owner is present right now." It does not unlock anything cryptographically. An attacker who can modify your running app (on a compromised device) can flip that boolean. For real protection, tie the secret to the biometric check by storing the item in the Keychain with an access-control rule such as "require the current biometric set" or "require user presence." Then the system itself refuses to release the item until the user authenticates. Use the plain LAContext check for convenience and for lower-risk screens, and Keychain access control for secrets that matter.

Modelling the outcomes

The next stand-in does not call any system API. It models the part you control: how your app responds to each result. Writing this mapping as a plain function makes it easy to test and ensures nothing is forgotten.

Swift Mapping biometric results to app behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The switch has no default, so adding a new result later makes the compiler point at every place that needs a decision. After three misses the app offers the passcode instead of looping forever, and a success resets the counter. The system also enforces its own lockout, so this is about good manners, not about security.

Secrets do not belong in your app

Anything inside your app bundle can be extracted. An app binary is a file the user owns, and people can read its strings, its resources and its network traffic.

  • API keys that grant paid or private access should not ship in the app. Put them on your server and let the app call your server, which calls the third-party service. Where a key must be in the app (a public map key, say), restrict it in the provider's dashboard to your bundle identifier and to the narrowest permissions.
  • Short-lived tokens beat long-lived passwords. Log in once, receive a token that expires, and keep only the token, in the Keychain.
  • Never log secrets. Print statements and crash logs end up in places you do not control.
  • Do not hide secrets with clever obfuscation. It slows down only the laziest attacker.

Network security: App Transport Security

By default iOS requires apps to use secure connections. App Transport Security (ATS) blocks plain http:// requests and requires modern TLS. This is good. If a request to an http:// address fails, the fix is almost always to use https:// on the server.

If you absolutely must reach a server that cannot do HTTPS, you can add an exception for that specific domain in Info.plist under NSAppTransportSecurity. Avoid the blanket NSAllowsArbitraryLoads setting. It disables protection for every connection, and App Review may ask you to justify it. Local development against localhost has its own allowance, so you rarely need a broad exception. Networking details are in URLSession with async/await.

Jailbreaks and trusting the device

You will read advice that says "detect jailbroken devices and refuse to run." Be careful with it.

  • Detection checks (does a certain file exist? can I write outside the sandbox?) are easy to defeat on a jailbroken device, so they give weak protection.
  • A rule of thumb for all client code: assume the client can be modified. Check permissions, prices and limits on the server, never only in the app.
  • iOS already encrypts data at rest and sandboxes apps. File protection settings control when your files can be read, for example only while the device is unlocked.
  • For stronger assurance that requests come from your genuine app, Apple provides services such as App Attest, which your server can verify. That is an advanced topic you only need for high-risk apps.

Privacy manifests

A privacy manifest is a file named PrivacyInfo.xcprivacy in your app (and in each third-party SDK you ship). It declares, in a structured way:

  • which kinds of data your app collects and why,
  • whether it uses data for tracking, and which tracking domains it contacts,
  • which "required reason" APIs it calls. These are APIs that could be used to fingerprint a device, such as UserDefaults, file timestamps, system boot time and disk space. For each, you give an approved reason.

App Store Connect checks the manifests when you upload a build, and may reject builds that use these APIs without a declared reason. Xcode can combine the manifests of your app and its frameworks into a privacy report, which helps you fill in the App Store privacy labels. The takeaway: know what your app and its SDKs collect, and keep the manifest up to date. Release steps are in Signing, TestFlight and App Store Release.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should an app store a user's login token?

    The Keychain is designed for small secrets such as tokens and passwords. UserDefaults and plain files are not meant for them, and source code can be extracted.
  2. 2. You call SecItemAdd for a service and account that already exist. What status do you get?

    An item is identified by its class, service and account. Adding the same one again returns errSecDuplicateItem, so apps update the existing item instead.
  3. 3. What does a true result from evaluatePolicy prove?

    It is a boolean gate. For strong protection, store the secret in the Keychain with an access-control requirement so the system itself withholds it until the user authenticates.
  4. 4. Which Info.plist entry explains to the user why the app uses Face ID?

    NSFaceIDUsageDescription holds the explanation text. Without it, Face ID requests fail on devices that have Face ID.
  5. 5. A third-party API key must be kept secret. What is the safest design?

    Anything shipped inside the app can be extracted. A server can keep the key private and enforce limits.

Summary

  • The Keychain is the system store for small secrets; its four calls are SecItemAdd, SecItemCopyMatching, SecItemUpdate and SecItemDelete, and you must always check the status.
  • An item is identified by class, service and account; duplicates return errSecDuplicateItem and missing items errSecItemNotFound.
  • kSecAttrAccessible controls when an item can be read; prefer strict values and ThisDeviceOnly when sync is not needed.
  • LocalAuthentication gives you a yes or no from Face ID, Touch ID or the passcode; it needs NSFaceIDUsageDescription, and every outcome (cancel, fallback, lockout, not enrolled) needs handling.
  • A boolean biometric check is a gate; tie high-value secrets to Keychain access control.
  • Do not ship secrets in the app, keep App Transport Security on, never trust the client alone, and keep privacy manifests accurate.

Next: Concurrency in iOS: MainActor, Tasks and Async Work