iOS Application Security
A Practical Guide: From Data Storage to Runtime Integrity
Mobile apps hold some of the most sensitive data a user has. Apple gives you a strong platform (sandboxing, Secure Enclave, Data Protection, App Transport Security), but the platform only protects you if you use it correctly. This guide covers current best practices for Swift apps, mapped loosely to the OWASP MASVS v2 categories. MASVS is the reference standard worth bookmarking.
1. Secure Data Storage
UserDefaults: preferences only
Use UserDefaults for non-sensitive values: theme, language, onboarding flags.
❌ Never store tokens, passwords, API keys or PII there. It is an unencrypted plist inside your container. It ends up in backups and can be read on a jailbroken device.
📌 Note: UserDefaults is a required-reason API. You must declare why you use it in your PrivacyInfo.xcprivacy privacy manifest, or App Store Connect will reject the build.
Keychain: the home for secrets
struct KeychainError: Error { let status: OSStatus }func saveToken(_ token: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.myapp.auth",
kSecAttrAccount as String: "accessToken"
]
let attributes: [String: Any] = [
kSecValueData as String: Data(token.utf8),
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) }
}
Key points:
- Always check
OSStatus. Silent failures are how tokens go missing. - Prefer
…ThisDeviceOnlyfor tokens, so they never migrate to another device through backups. AfterFirstUnlockis needed if you refresh tokens in the background. Otherwise useWhenUnlocked.
Biometric-protected items (Face ID / Touch ID)
var error: Unmanaged<CFError>?
guard let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.biometryCurrentSet,
&error
) else { throw error!.takeRetainedValue() as Error }let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.myapp.auth",
kSecAttrAccount as String: "secureToken",
kSecValueData as String: Data(token.utf8),
kSecAttrAccessControl as String: access
].biometryCurrentSetinvalidates the item if the user enrolls a new face or fingerprint. That is exactly what you want for high-value secrets.WhenPasscodeSetdeletes the item if the passcode is removed.- ⚠️ A plain
LAContext.evaluatePolicycheck without a Keychain item is just a UI gate and can be bypassed by hooking. Tie biometrics to a Keychain item or a Secure Enclave key.
Files and databases: Data Protection
try data.write(to: url, options: .completeFileProtection)Set Data Protection to Complete for any file, SQLite, Core Data or SwiftData store that holds user data. You can also set a default for the whole app with the Data Protection capability.
Don’t forget the “leaky” places
- App switcher snapshots: hide sensitive screens when the scene moves to the background.
- Pasteboard: use
UIPasteboardwith.localOnlyand.expirationDatefor copied secrets. - Keyboard cache: use
isSecureTextEntryand.textContentTypecorrectly on sensitive fields.
2. Authentication
Passkeys first
Passwords are the weakest link. Passkeys (WebAuthn/FIDO2) are phishing-resistant and synced through iCloud Keychain. Support them wherever your backend can:
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
relyingPartyIdentifier: "myapp.com")
let request = provider.createCredentialAssertionRequest(challenge: serverChallenge)let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()This needs Associated Domains (webcredentials:myapp.com).
OAuth 2.0 done right
- Use Authorization Code + PKCE. The implicit flow is deprecated.
- Use
ASWebAuthenticationSession, never an embeddedWKWebView, for login pages. - Keep access tokens short-lived. Use refresh token rotation and revoke tokens on logout.
JWT reminders
- JWTs are signed, not encrypted. Anyone can read the payload, so keep sensitive data out of it.
- The client should never trust a JWT for authorization decisions. The server validates the token.
3. Secure Network Communication
App Transport Security
ATS enforces HTTPS with TLS 1.2+ by default. Don’t add NSAllowsArbitraryLoads. If you need an exception, scope it to a single domain and justify it in App Review.
Certificate pinning: the declarative way
Since iOS 14 you can pin in Info.plist with no custom URLSessionDelegate code:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSPinnedDomains</key>
<dict>
<key>api.myapp.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSPinnedCAIdentities</key>
<array>
<dict>
<key>SPKI-SHA256-BASE64</key>
<string>PRIMARY_PIN_BASE64</string>
</dict>
<dict>
<key>SPKI-SHA256-BASE64</key>
<string>BACKUP_PIN_BASE64</string>
</dict>
</array>
</dict>
</dict>
</dict>- Pin public keys (SPKI), not certificates. Always ship a backup pin.
- Pinning to your CA or intermediate is more forgiving than pinning the leaf certificate.
- Have a rotation plan. A bad pin can brick your app’s networking until users update.
4. App & Device Integrity
Jailbreak detection: useful signal, weak defense
Classic checks (Cydia paths, /bin/bash, writing outside the sandbox) are outdated. Modern rootless jailbreaks live under /var/jb, and hooking frameworks can fake FileManager results. If you do local checks:
- Combine several signals: suspicious paths, loaded dylibs, sandbox violations, debugger attachment.
- Treat the result as a risk signal you send to your backend, not as a hard kill switch.
App Attest: the modern answer
DCAppAttestService lets your server cryptographically verify that requests come from a genuine, unmodified copy of your app on a real Apple device:
let service = DCAppAttestService.shared
guard service.isSupported else { return /* fallback policy */ }let keyId = try await service.generateKey()
let clientDataHash = Data(SHA256.hash(data: serverChallenge))
let attestation = try await service.attestKey(keyId, clientDataHash: clientDataHash)
// Send keyId + attestation to your server for verification,
// then sign sensitive requests with generateAssertion(_:clientDataHash:)Combine it with DeviceCheck (per-device bits) for fraud and abuse cases. Enforcement happens on the server, where attackers can’t patch it out.
Obfuscation
Obfuscation (renaming symbols, encrypting strings, anti-tamper and anti-debug checks) raises the cost of reverse engineering. Commercial tools such as iXGuard are the practical option today. Obfuscation is still just one layer. It never makes an embedded secret safe.
5. Secure Coding Practices
Logging with privacy built in
import OSLog
let logger = Logger(subsystem: "com.myapp", category: "auth")
logger.info("Login succeeded for \(userId, privacy: .private)")
logger.debug("Token refreshed") // log the event, never the token- Interpolated values are redacted by default in
Logger. Mark only safe values as.public. print()isn't redacted and ships in release builds unless you strip it.- Watch out for crash reporters and analytics SDKs. They are logs too.
No hardcoded secrets
Anything in your binary can be extracted: API keys, client secrets, encryption keys. Instead:
- Keep real secrets on the server and proxy third-party calls through your backend.
- Use short-lived, scoped tokens issued after authentication (ideally gated by App Attest).
- Keep
.xcconfigfiles and CI secrets out of Git.
Swift 6 helps
Strict concurrency checking removes whole classes of data-race bugs. Some of these lead to security issues such as TOCTOU (time-of-check to time-of-use) races around auth state. Enable it on new code.
6. Cryptography with CryptoKit
Instead of choosing to write your own cryptography system, use CryptoKit.
Get Gaye Uğur’s stories in your inbox
Join Medium for free to get updates from this writer.
Authenticated encryption (AES-GCM):
let key = SymmetricKey(size: .bits256)
let sealed = try AES.GCM.seal(plaintext, using: key)
let stored = sealed.combined! // nonce + ciphertext + tag
let decrypted = try AES.GCM.open(AES.GCM.SealedBox(combined: stored), using: key)Store the key in the Keychain, never next to the data.
Secure Enclave keys (private key never leaves the hardware):
if SecureEnclave.isAvailable {
let key = try SecureEnclave.P256.Signing.PrivateKey()
let signature = try key.signature(for: payload)
// Persist key.dataRepresentation in the Keychain. It is only usable on this device.
}Hashing: SHA256 is fine for integrity checks and fingerprints. It is not for passwords. Password hashing (Argon2, bcrypt, scrypt) belongs on the server.
Recent iOS versions also add post-quantum algorithms to CryptoKit and TLS. You get the TLS protection automatically through URLSession, which is one more reason to use system networking rather than custom stacks.
7. Injection and WebView Risks
SQL injection is a local risk too
Many apps use SQLite on-device. Never build queries with string interpolation:
// ❌ Unsafe
let sql = "SELECT * FROM users WHERE email = '\(email)'"
// ✅ Safe: bound parameters
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
sqlite3_prepare_v2(db, "SELECT * FROM users WHERE email = ?", -1, &stmt, nil)
sqlite3_bind_text(stmt, 1, email, -1, SQLITE_TRANSIENT)Higher-level layers such as SwiftData, Core Data or GRDB (with arguments) handle this for you.
WKWebView hardening
- Disable JavaScript when it isn’t needed:
WKWebpagePreferences.allowsContentJavaScript = false. - Allowlist hosts in
decidePolicyFor navigationAction. - Treat every
WKScriptMessageHandlermessage as untrusted input and validate it. - Never expose native functionality to a WebView that loads remote or third-party content.
Deep links and Universal Links
URL parameters are attacker-controlled input. Validate them, and never let a deep link trigger a sensitive action (payments, account changes) without re-authentication. Prefer Universal Links over custom URL schemes, since any app can claim a custom scheme.
8. Third-Party Dependencies & Supply Chain
- Migrate to Swift Package Manager. CocoaPods’ central Specs repo (trunk) is moving to read-only, so new versions will stop arriving there.
- Pin versions and commit
Package.resolved. - Require privacy manifests and signatures from third-party SDKs. Xcode verifies SDK signatures, and Apple requires them for commonly used SDKs.
- Audit what each SDK collects and sends. Its data practices become yours in your App Store privacy labels.
- Remove unused dependencies, and watch for security advisories.
9. Security Checklist
AreaDoStorageSecrets → Keychain (ThisDeviceOnly), files → Complete Data ProtectionAuthPasskeys, OAuth + PKCE via ASWebAuthenticationSession, short-lived tokensNetworkATS on, SPKI pinning via NSPinnedDomains with backup pinsIntegrityApp Attest verified on the server; jailbreak checks only as a signalCodeLogger with privacy, no hardcoded secrets, Swift 6 concurrencyCryptoCryptoKit only: AES-GCM, Secure Enclave keysInputParameterized SQL, hardened WebViews, validated deep linksSupply chainSPM, pinned versions, SDK privacy manifests and signatures
Conclusion: Defense in Depth
No single control makes an app secure. The client is ultimately in the attacker’s hands, so anything that really matters must be enforced on the server. The job of the app is to protect data at rest, protect it in transit, and give the server trustworthy signals: Passkeys, App Attest, pinned TLS.
“Security is not a feature, it is a process.”
Revisit this every WWDC. Apple adds new protections every year, and the best ones are often a single capability or Info.plist key away.







