Security and Authentication

Article · 2:00

Why a token never goes in UserDefaults, and how a sign-in flow is actually shaped.

UserDefaults is a plain property list inside your app's container. It is not encrypted, and on a device that has been jailbroken or restored from an unencrypted backup it can be read. An access token, a refresh token, a password or an API key therefore never goes there. They go in the Keychain, which is encrypted by the system, protected by the device passcode and survives reinstalling the app.

The Keychain API is C-shaped and unpleasant, which is why almost every project wraps it. Write the wrapper once - save, read, delete, keyed by a string - and the rest of your code never sees a CFDictionary again. Choose the accessibility level deliberately: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly is the sensible default for a token, because it is available to background work after the first unlock but never leaves the device in a backup.

The shape of a login flow is the same everywhere. Exchange credentials for a short-lived access token and a long-lived refresh token; keep both in the Keychain; attach the access token to each request; when a request answers 401, use the refresh token once to get a new pair and retry. Sign out means deleting from the Keychain, not just clearing a variable. For anything consumer-facing, offer Sign in with Apple - on an app that offers other third-party logins, App Review requires it.

import Foundation
import Security

// The Keychain, wrapped once so nothing else has to see the C API.
enum TokenStore {
    private static let service = "com.example.app.tokens"

    static func save(_ token: String, account: String) throws {
        let data = Data(token.utf8)
        // Delete any existing item first: SecItemAdd fails on a duplicate.
        SecItemDelete([
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: account,
        ] as CFDictionary)

        let status = SecItemAdd([
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: account,
            kSecValueData: data,
            // Available after first unlock, and never in a backup.
            kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
        ] as CFDictionary, nil)

        guard status == errSecSuccess else { throw KeychainError.status(status) }
    }

    static func read(account: String) -> String? {
        var item: CFTypeRef?
        let status = SecItemCopyMatching([
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: service,
            kSecAttrAccount: account,
            kSecReturnData: true,
        ] as CFDictionary, &item)

        guard status == errSecSuccess, let data = item as? Data else { return nil }
        return String(decoding: data, as: UTF8.self)
    }

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

enum KeychainError: Error { case status(OSStatus) }