Skip to content
Commitwise
Menu
iOS Development

App security: Keychain, ATS and pinning

Store tokens and secrets safely in the Keychain with the right accessibility, protect files with Data Protection, gate sensitive actions with Face ID, keep traffic on HTTPS with App Transport Security, pin certificates without locking users out, and know what jailbreak checks and App Attest can and can't do.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A security review of the banking app comes back with four findings. The refresh token is stored in UserDefaults, readable in an unencrypted device backup. A third-party analytics key is a string constant, easy to extract from the binary. A debug flag once turned off certificate validation and nobody turned it back on. And when users delete and reinstall the app, they’re still logged in.

None of these need exotic tools to find, and all of them have standard fixes on iOS: the Keychain for secrets, Data Protection for files, App Transport Security for traffic, and careful pinning for high-value APIs. This lesson covers what each one protects against, and where it stops.

New to some of these? Open what you need, or skip ahead.

Basics:What is a token?

After you sign in, the server gives the app a token: a long random string that proves who you are on later requests, so the app doesn’t have to keep your password. An access token is short-lived (minutes or hours); a refresh token lasts longer and is used to get new access tokens. Anyone who steals a token can act as you until it expires, so it must be stored safely. See also JWT (JSON Web Token)JWT (JSON Web Token)A signed token that carries claims (who the user is, what they may do, when it expires), so a server can verify a request without a database lookup.Open in glossary →.

Basics:What is HTTPS?

HTTPS is HTTP over an encrypted connection (TLS). The server proves its identity with a certificate signed by a trusted certificate authority, and everything sent is encrypted, so people on the same Wi-Fi can’t read or change it. Plain http:// sends everything as readable text.

Part Not started

Storing secrets

UserDefaults is like a notebook left on the table: fine for settings such as “dark mode on”, but anyone who gets the phone’s backup can read it. The KeychainKeychainThe encrypted store iOS provides for passwords, tokens and keys, private to the app unless shared through an access group.Open in glossary → is a safe built into iOS. It encrypts what you put in it with keys tied to the device and the passcode, and only your app can open its own items.

What goes where:

  • Keychain: tokens, passwords, encryption keys, anything that lets someone act as the user.
  • UserDefaults: settings and small flags.
  • Files: larger data, protected with Data Protection (encrypted while the phone is locked).

The Keychain’s API is old and dictionary-based, so every app wraps it in a small helper like the one below.

Keychain items are encrypted with class keys derived from the device UID and (for most classes) the passcode; the accessibility attribute picks the class. kSecAttrAccessibleWhenUnlocked is the safest default for foreground use; anything read by background work (background refresh, push handling, a background URLSession delegate) needs AfterFirstUnlock, or reads fail with errSecInteractionNotAllowed while the device is locked. The ThisDeviceOnly variants exclude the item from backups and device migration, which is what you want for tokens. Items persist across app deletion (the Keychain isn’t part of the app container), share across your apps and extensions only through an explicit access group, and can require user presence via SecAccessControl (.biometryCurrentSet invalidates the item when Face ID enrollment changes). Files use Data Protection classes (.complete, .completeUnlessOpen, .completeUntilFirstUserAuthentication, the default). And anything compiled into the binary, including obfuscated API keys, should be treated as public: secrets that matter belong on your server.

import Security

struct KeychainError: Error { let status: OSStatus }

enum Keychain {
    private static let service = "com.example.bank.auth"

    static func save(_ data: Data, for account: String) throws {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
        ]
        let attributes: [String: Any] = [
            kSecValueData as String: data,
            // Readable after the first unlock since boot (needed by background refresh), never backed up
            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
        ]
        var status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
        if status == errSecItemNotFound {
            status = SecItemAdd(query.merging(attributes) { $1 } as CFDictionary, nil)
        }
        guard status == errSecSuccess else { throw KeychainError(status: status) }
    }

    static func read(_ account: String) throws -> Data? {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne,
        ]
        var result: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        if status == errSecItemNotFound { return nil }
        guard status == errSecSuccess else { throw KeychainError(status: status) }   // e.g. locked device
        return result as? Data
    }

    static func delete(_ account: String) {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
        ]
        SecItemDelete(query as CFDictionary)
    }
}

// Files: encrypted whenever the device is locked
try data.write(to: url, options: .completeFileProtection)
  • kSecClassGenericPassword is the item type for passwords and tokens. service + account together are the item’s name, like a label on a drawer.
  • SecItemUpdate, then SecItemAdd: update the item if it exists, otherwise create it. Adding an item that already exists fails with errSecDuplicateItem.
  • kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly: readable once the user has unlocked the phone after turning it on, and never copied to backups or a new phone.
  • read throws for real errors, so a locked device isn’t mistaken for “no token”. Treating every error as “not logged in” is how apps log users out at random.
Spot the bugLogin that survives too much

Tap the line with the bug.

final class AuthStore {
    func didLogIn(token: String, refreshToken: String) {
        UserDefaults.standard.set(token, forKey: "accessToken")
        UserDefaults.standard.set(refreshToken, forKey: "refreshToken")
    }

    var isLoggedIn: Bool {
        UserDefaults.standard.string(forKey: "refreshToken") != nil
    }
}

Predict the output

A user logs in, deletes the app, and installs it again from the App Store. On first launch the app checks Keychain.read("refreshToken"). What does it find?

Asking for Face ID before showing something

For sensitive screens (card details, a password vault), ask for Face ID or Touch ID first with LocalAuthentication. Add NSFaceIDUsageDescription to Info.plist, a sentence explaining why.

import LocalAuthentication

func unlockCardDetails() async -> Bool {
    let context = LAContext()
    var error: NSError?
    // .deviceOwnerAuthentication falls back to the passcode if Face ID fails or isn't set up
    guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { return false }
    do {
        return try await context.evaluatePolicy(.deviceOwnerAuthentication,
                                                localizedReason: "Show your card details")
    } catch {
        return false   // the user cancelled or failed
    }
}

This only asks the user. The card details themselves still come from the server or the Keychain; Face ID is a gate in front of them, not encryption.

Biometrics that actually protect the data

A bare LAContext.evaluatePolicy returns a Bool in your process: on a compromised device it can be hooked to return true. To make biometrics protect the data, put the secret in a Keychain item with an access control; the Secure Enclave then refuses to release it without a successful match:

let access = SecAccessControlCreateWithFlags(
    nil,
    kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,   // removed if the passcode is turned off
    .biometryCurrentSet,                                // invalidated when Face ID enrollment changes
    nil
)!
let query: [String: Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrService as String: "com.example.bank.vault",
    kSecAttrAccount as String: "cardKey",
    kSecValueData as String: cardKey,
    kSecAttrAccessControl as String: access,
]
SecItemAdd(query as CFDictionary, nil)
// Reading it shows the Face ID prompt; pass an LAContext in kSecUseAuthenticationContext to customize it.

For keys that should never leave the hardware at all (signing a login challenge, for example), generate them in the Secure Enclave with CryptoKit’s SecureEnclave.P256.Signing.PrivateKey: the app gets a handle and signatures, never the key bytes.

NeedUse
Tokens used by background workKeychain, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
Foreground-only secretsKeychain, WhenUnlocked(ThisDeviceOnly)
Data released only after Face IDKeychain item with SecAccessControl(.biometryCurrentSet)
Keys that never leave hardwareCryptoKit SecureEnclave.P256 keys
FilesData Protection: .completeFileProtection where possible
Sharing with extensionsKeychain access group + App Group container
  • Keychain survives app deletion: detect a fresh install and wipe. ThisDeviceOnly keeps items out of backups and migrations.
  • errSecInteractionNotAllowed = device locked for that class; never treat it as “logged out”.
  • LAContext.evaluatePolicy alone is a UI gate, not protection. Secrets in the binary are public.

Check this part

  1. Where should an app store a refresh token?

  2. The app is deleted and reinstalled. What happens to its Keychain items?

  3. A background refresh reads a token stored with WhenUnlocked while the phone is locked. Result?

  4. What makes Face ID protect data rather than just show a prompt?

Tokens and passwords go in the Keychain, never in UserDefaults or plain files. Pick accessibility on purpose: AfterFirstUnlockThisDeviceOnly for tokens used in the background, WhenUnlocked for the rest, ThisDeviceOnly to keep secrets out of backups. Keychain items survive app deletion, so clear them on the first launch after install. Biometrics guard an item with SecAccessControl. Secrets compiled into the app are public.

Part Not started

Safe traffic and an untrusted device

iOS helps by default: App Transport Security (ATS)App Transport SecurityAn iOS policy that blocks plain HTTP and weak TLS for the app's network connections unless an exception is declared.Open in glossary → blocks plain http:// requests and weak encryption. If a request to http:// fails with an ATS error, the fix is almost always to use https://, not to switch ATS off.

Certificate pinningCertificate pinningTrusting only specific server keys for a domain, instead of any certificate a trusted authority has issued.Open in glossary → goes one step further. Normally the app trusts any valid certificate for api.example.com. With pinning, it trusts only your server’s key, so even someone who tricks the phone into trusting a fake certificate can’t read the traffic. Banks and payment apps use it. The risk: if your server’s key changes and the app doesn’t know the new one, every request fails until users update the app. So pins always come with a backup pin.

A few habits protect users on the device itself:

  • Hide sensitive screens in the app switcher (the snapshot iOS takes when you leave the app).
  • Don’t log tokens, card numbers or personal data. Logs end up in crash reports and support tickets.
  • Don’t trust the device. Checks for jailbreaks can be bypassed; the server must validate everything.

ATS enforces HTTPS with TLS 1.2+ and forward secrecy for URLSession; per-domain exceptions (NSExceptionDomains) should be rare and justified (App Review asks). The classic critical bug is a URLSessionDelegate that answers server-trust challenges with .useCredential without evaluating the trust, which silently accepts any certificate. Pinning narrows trust from “any CA-issued certificate” to specific keys, defending against mis-issued certificates and user-installed root CAs (corporate proxies, malware profiles). Pin the SPKI hash (public key), not the certificate, so renewals with the same key don’t break; include at least one backup key that isn’t deployed yet; pin an intermediate CA if you rotate leaf keys often; and have a kill switch (a remote config that relaxes pinning) only if it can’t itself be spoofed. Since iOS 14, NSPinnedDomains in Info.plist does this declaratively for URLSession. On the device side, assume compromise: jailbreak detection and anti-debugging are speed bumps; App Attest (DeviceCheck) gives your server cryptographic evidence that a request comes from a genuine instance of your app on a real Apple device, which is what fraud-sensitive endpoints should rely on.

// Cover the app switcher snapshot on sensitive screens
struct CardDetailsView: View {
    @Environment(\.scenePhase) private var scenePhase

    var body: some View {
        CardDetails()
            .overlay {
                if scenePhase != .active {
                    Rectangle().fill(.regularMaterial).ignoresSafeArea()
                }
            }
    }
}
<!-- Info.plist: pin the public keys of api.example.com (current key + an undeployed backup) -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSPinnedDomains</key>
    <dict>
        <key>api.example.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSPinnedLeafIdentities</key>
            <array>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E=</string>
                </dict>
                <dict>
                    <key>SPKI-SHA256-BASE64</key>
                    <string>YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=</string>
                </dict>
            </array>
        </dict>
    </dict>
</dict>
  • The two strings are hashes of public keys: the current one and a backup that the server team keeps ready. Your backend or security team generates them from the server’s certificates.
  • With this in Info.plist, URLSession rejects any connection to api.example.com whose key doesn’t match, with no extra code.
  • The overlay covers the screen as soon as the app becomes inactive, so the app switcher shows a blur instead of card numbers.

Production puzzles

Spot the bugThe staging fix that shipped

Tap the line with the bug.

final class APISessionDelegate: NSObject, URLSessionDelegate {
    func urlSession(
        _ session: URLSession,
        didReceive challenge: URLAuthenticationChallenge
    ) async -> (URLSession.AuthChallengeDisposition, URLCredential?) {
        guard let trust = challenge.protectionSpace.serverTrust else {
            return (.performDefaultHandling, nil)
        }
        // Staging uses a self-signed certificate
        return (.useCredential, URLCredential(trust: trust))
    }
}

Predict the output

The app pins only the current leaf key of api.example.com. The ops team renews the certificate with a newly generated key on Friday evening. What happens on Monday?

Exercisehard

Threat model a payments screen

A “send money” flow: the user picks a contact, enters an amount, confirms with Face ID, and the app calls POST /transfers. List the main threats and the controls you’d put in the app and on the server.

›

Think about who can attack: someone on the network, someone holding the unlocked phone, malware on a jailbroken device, and someone calling your API directly without the app.

SolutionTry it yourself first
  • Network attacker: HTTPS via ATS, public key pinning with backups for the payments API, no trust-evaluation shortcuts.
  • Stolen token: short-lived access tokens, refresh token in Keychain ThisDeviceOnly, server-side revocation and device binding.
  • Someone with the phone: Face ID enforced through a Keychain item or a Secure Enclave key that signs the transfer request, so the server can verify the user was present; a passcode fallback policy; snapshot hiding.
  • Scripts calling the API directly: App Attest assertions on transfer requests, rate limits, server-side limits and risk scoring.
  • Replay and duplicates: an idempotency key per transfer and a server nonce in the signed payload.
  • Everything else: the server validates amounts, ownership and limits; nothing the client says is trusted on its own.
Exercisemedium

Review the settings screen

A teammate’s pull request for a “Connected accounts” screen: it saves the user’s email and the third-party service’s access token in UserDefaults, prints the token with print("token:", token) for debugging, and adds NSAllowsArbitraryLoads = YES to Info.plist because the partner’s sandbox only has http://. Write three review comments.

›

Go through what this lesson said about storage, logs and App Transport Security.

SolutionTry it yourself first
  1. The token belongs in the Keychain, not UserDefaults, which ends up in backups. The email can stay in UserDefaults if it’s only shown in the UI.
  2. Remove the print of the token. Logs can end up in crash reports and screenshots; log that a token exists, never its value.
  3. Don’t turn off ATS for the whole app. If the sandbox really can’t use HTTPS, add a narrow exception for that one domain in the Debug configuration only, and make sure production uses HTTPS.
  • ATS: HTTPS, TLS 1.2+, forward secrecy; narrow NSExceptionDomains only. Never .useCredential without SecTrustEvaluateWithError.
  • Pin SPKI hashes, not certificates; always an undeployed backup; consider pinning an intermediate; written rotation process. NSPinnedDomains (iOS 14+) for declarative pinning.
  • Device is untrusted: jailbreak checks are speed bumps; App Attest gives the server evidence of a genuine app instance; server validates everything.
  • Snapshot covers on sensitive screens; no tokens or personal data in logs or analytics.

Check this part

  1. A request to http:// fails with an App Transport Security error. Best fix?

  2. Why does certificate pinning always include a backup pin?

  3. A trust delegate returns .useCredential without evaluating the trust. What does it accept?

  4. What lets a server verify that a request comes from your genuine app?

App Transport Security requires HTTPS with modern TLS; keep exceptions narrow and never disable certificate validation in a URLSession delegate. Pin public keys (NSPinnedDomains or SecTrust checks) only for high-value APIs, always with backup pins and a rotation plan. Jailbreak detection is a speed bump; App Attest lets your server verify requests come from your genuine app. Hide sensitive screens in the app switcher and keep personal data out of logs.

Key takeaways

  • Tokens and passwords go in the Keychain; settings go in UserDefaults.
  • Keychain items survive reinstalls: clear them on a fresh install.
  • Keep App Transport Security on and use HTTPS.
  • Pinning protects high-value APIs but needs backup pins.
  • Don’t log secrets, and hide sensitive screens in the app switcher.
  • Choose Keychain accessibility for when the item is read; ThisDeviceOnly for tokens.
  • Bind biometrics to data with access control or Secure Enclave keys, not a Bool.
  • Pin public keys with backups and a rotation process; never short-circuit trust evaluation.
  • Treat the client as untrusted; App Attest and server-side checks carry the weight.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.