What are the best practices for managing app secrets (API keys, passwords) in iOS?
Instruction: Discuss methods for securely storing and accessing sensitive information within an iOS application.
Updated
Official answer
Separate server secrets from credentials the installed app legitimately needs. A privileged service key must stay on a controlled server, which authorizes each user's requested action. A secret injected into a binary by CI, encoded in a resource or fetched for every installation can still be extracted from a client under an attacker's control. Keeping it out of source control is useful, but does not make it confidential on the device.
Treat public app identifiers and provider-designated public API keys according to the provider's restriction model; they are not substitutes for user authorization. For native OAuth, use an appropriate public-client flow with an external user agent and PKCE rather than relying on a shared client secret. Prefer revocable, narrowly scoped tokens to collecting and retaining user passwords.
Store appropriate small user credentials in Keychain, handle API status codes and choose accessibility deliberately. WhenUnlockedThisDeviceOnly restricts access to an unlocked device and prevents migration to another device. AfterFirstUnlockThisDeviceOnly can support background access after the first unlock following restart, even while subsequently locked. The setting must match the task and threat model; Keychain is not universally inaccessible whenever the screen is locked.
Keep secrets out of logs, analytics, pasteboards and ordinary preferences. Limit access groups and entitlements, clear or revoke credentials according to account policy, and plan token expiry, rotation and recovery. Use normal TLS certificate validation and never bypass trust checks to make a failing connection work. TLS protects the transport under its trust assumptions; it does not protect against a compromised endpoint or grant authorization.
Obfuscation can add extraction effort but cannot establish a secure secret boundary. Verify the relevant device and locked/background states and have a concrete response for a leaked credential.
Keychain services, Unlocked-device access, After-first-unlock access, Native OAuth public-client security