Join our Newsletter — 33% off our NHI Course
Home› Guides› Swift and iOS Secure Coding Guide: Keychain, Transport…
Guide Application Security

Swift and iOS Secure Coding Guide: Keychain, Transport and Data Protection

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 8 November 2026 15 min read
On this page

iOS gives Swift developers strong security primitives, yet most iOS app findings come from how the code calls them: a token in UserDefaults, a Face ID check that returns a Boolean nobody can trust, a URLSession delegate that accepts any certificate, or an archive decoded without a class check. Swift's memory safety removes whole classes of bugs, but it does not validate a universal link parameter or choose a keychain accessibility class for you. This guide is the code-level companion to the iOS App Security Guide: that page explains the platform controls (Data Protection classes, the accessibility table, App Attest and privacy manifests), while this one shows how to use them correctly in Swift and which patterns code review should reject. Each section maps to the OWASP Mobile Top 10 2024 and MASVS. It is written for iOS developers, mobile code reviewers and application security engineers. See the iOS App Security Guide.

This is an independent guide from NHI Mgmt Group, based on Apple's public documentation as of November 2026. It is not sponsored or reviewed by Apple. Product features change, so confirm settings against Apple's current documentation.

Key takeaways

  • Gate secrets with the keychain, not with an if statement. Store tokens with a SecAccessControl such as .userPresence and kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, so the Secure Enclave decides access rather than a Boolean in your code.
  • Use CryptoKit and nothing lower. Apple recommends CryptoKit over lower-level interfaces; it handles memory and offers AES.GCM, ChaChaPoly, HPKE, Secure Enclave keys and quantum-secure ML-KEM and ML-DSA.
  • Never answer a trust challenge with blind acceptance. Let App Transport Security and default evaluation do their job, and pin through NSPinnedDomains in Info.plist rather than hand-written delegate code.
  • Decode only the classes you expect. NSSecureCoding with decodeObject(of:forKey:) and unarchivedObject(ofClass:from:) stops object substitution; typed Codable models do the same for JSON.
  • Every URL into your app is untrusted. Prefer universal links over custom schemes, validate parameters against an allowlist, and never let a link choose what a WKWebView loads or which action runs without authorisation.

Mapping the OWASP Mobile Top 10 to Swift code

The table shows where each OWASP Mobile Top 10 2024 risk usually appears in a Swift codebase and the coding control that addresses it. See the OWASP Mobile Top 10 Guide.

OWASP Mobile 2024Where it appears in Swift and iOS codePrimary coding controlMASVS
M1 Improper Credential UsageAPI keys in Info.plist, xcconfig or Swift constants; tokens in UserDefaultsKeychain items with access control; backend token exchangeMASVS-STORAGE, MASVS-AUTH
M2 Inadequate Supply Chain SecurityUnpinned Swift packages, opaque binary XCFrameworks, SDKs with embedded keysCommitted Package.resolved, SDK review, privacy manifestsMASVS-CODE
M3 Insecure Authentication/AuthorizationLAContext.evaluatePolicy result used as the only gateKeychain items protected by SecAccessControl; server-side authorisationMASVS-AUTH
M4 Insufficient Input/Output ValidationonOpenURL handlers, WKScriptMessageHandler, NSKeyedUnarchiver, string-built SQLAllowlists, NSSecureCoding, typed Codable, bound SQLite parametersMASVS-CODE, MASVS-PLATFORM
M5 Insecure CommunicationURLSessionDelegate that trusts any server; ATS exceptionsDefault trust evaluation, NSPinnedDomains, no NSAllowsArbitraryLoadsMASVS-NETWORK
M6 Inadequate Privacy ControlsPII in os_log or print, general pasteboard, app switcher snapshotsPrivate log interpolation, local pasteboards, snapshot redactionMASVS-PRIVACY
M7 Insufficient Binary ProtectionsSecrets relying on obfuscation, inspectable web views in releaseNo secrets in the binary; isInspectable false in releaseMASVS-RESILIENCE
M8 Security MisconfigurationBroad ATS exceptions, over-wide entitlements, custom URL schemes for sensitive flowsMinimal Info.plist exceptions and entitlements; associated domainsMASVS-PLATFORM
M9 Insecure Data StorageFiles without a Data Protection class, caches, Core Data stores with tokens.completeFileProtection writes, keychain for secretsMASVS-STORAGE
M10 Insufficient CryptographyCommonCrypto with ECB or static IVs, MD5 or SHA-1 for securityCryptoKit AEAD with fresh nonces; Insecure namespace only for legacy interopMASVS-CRYPTO

Keychain code that holds up

Apple's sample for protecting keychain items with Face ID or Touch ID shows the pattern that should be the default for any token or private key. It combines two dimensions in one SecAccessControl object: accessibility and authentication.

  • Create the access control: call SecAccessControlCreateWithFlags with kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly and .userPresence. That accessibility class refuses to store the item if the device has no passcode, makes existing items unavailable if the passcode is removed, and, because it ends in ThisDeviceOnly, keeps the item out of iCloud Keychain and out of backups restored to a new device. .userPresence asks for biometrics with a passcode fallback; use .biometryCurrentSet where enrolling a new fingerprint or face should invalidate access.
  • Add the item: build the query with kSecClass, kSecAttrAccount, kSecAttrAccessControl and kSecValueData, call SecItemAdd, and check the OSStatus. Handle errSecDuplicateItem by updating with SecItemUpdate rather than deleting and re-adding without access control.
  • Read with context: pass an LAContext through kSecUseAuthenticationContext and set localizedReason so the prompt explains why. touchIDAuthenticationAllowableReuseDuration lets a recent device unlock (up to five minutes) satisfy the check; keep it at zero for high-value operations.
  • Declare Face ID use: NSFaceIDUsageDescription must be present in Info.plist, or the system will not let the app use Face ID.
  • Skip prompts in bulk queries: when searching broadly, kSecUseAuthenticationUISkip returns unprotected items without prompting, instead of weakening the protection on the items themselves.

Why the Boolean is not enough

Calling LAContext.evaluatePolicy and then reading a token from UserDefaults or an unprotected keychain item means the only barrier is a Boolean in the app's own process, which runtime instrumentation on a compromised device can flip. With an access-controlled keychain item, the Secure Enclave performs the authentication and only releases the item on success; Apple's documentation notes that no user-space or operating system software ever sees the underlying biometric data. Reviewers should flag any evaluatePolicy call whose success branch reads a secret from somewhere other than an access-controlled keychain item. See the Biometrics Guide.

Cryptography with CryptoKit

Apple's CryptoKit documentation says to prefer CryptoKit over lower-level interfaces, because it frees the app from managing raw pointers and overwrites sensitive data when memory is deallocated. In practice, any new use of CommonCrypto or SecKey for symmetric encryption, hashing or key agreement in Swift should need a written justification.

NeedCryptoKit typeCoding note
Authenticated encryptionAES.GCM, ChaChaPoly with SymmetricKeyLet seal() generate the nonce; store the combined sealed box; never reuse a nonce with the same key
HashingSHA256, SHA384, SHA512, SHA3_256, SHA3_384, SHA3_512Hashes are not password storage; passwords belong on the server with a slow KDF
Message authenticationHMAC with SymmetricKeyCompare authentication codes with the type's own validation, not ==
Key derivationHKDFDerive per-purpose keys from a SharedSecret with distinct info values
Signatures and key agreementP256, P384, P521, Curve25519Use P256 when the key must live in the Secure Enclave
Hardware-bound keysSecureEnclave.P256Private key never leaves the enclave; persist only its dataRepresentation in the keychain
Public key encryptionHPKEPrefer to hand-assembled ECDH plus AES constructions
Quantum-secureMLKEM768, MLKEM1024, XWingMLKEM768X25519, MLDSA65, MLDSA87Use the hybrid X-Wing KEM for new long-lived confidentiality where both ends support it
Legacy onlyInsecure (container for older algorithms)Ban outside interoperability code with a lint rule

CryptoKit keys convert to and from native keychain types, so the storage rules above apply to them. A SymmetricKey created at runtime and written to a file or UserDefaults is a key stored in plain text. See the Post-Quantum Cryptography Migration Guide.

Transport security in Swift code

App Transport Security enforces HTTPS by default, and the iOS App Security Guide covers its keys. The code-level failure is a URLSessionDelegate whose urlSession(_:didReceive:completionHandler:) answers every server trust challenge with .useCredential and a URLCredential built from the presented trust, without evaluating it. That single method disables certificate validation for the whole session. Code review should treat any custom server trust handling as high risk; return .performDefaultHandling unless there is a documented need.

  • Pin declaratively: NSPinnedDomains (iOS and iPadOS 14 and later) takes, per domain, NSPinnedCAIdentities, NSPinnedLeafIdentities or both, each identified by an SPKI SHA-256 hash, with NSIncludesSubdomains to extend coverage. If both CA and leaf pins are given, a match is required in each. Pinning adds to, and does not replace, the system's normal evaluation. Pin a CA or intermediate plus a backup to survive certificate rotation. See the Certificate Expiry Outages and 47-Day TLS Certificates Guide.
  • Remove blanket exceptions: NSAllowsArbitraryLoads and broad NSExceptionDomains entries should not survive to release; App Store review asks for justification of ATS exceptions.
  • Check web content too: WKWebView exposes serverTrust and hasOnlySecureContent, which an in-app browser can use to warn on mixed content.
  • Keep tokens out of URLs: send bearer tokens in the Authorization header; query strings end up in logs and caches. Interception is tracked in ATT&CK for Mobile as T1638 Adversary-in-the-Middle.

Untrusted input: URLs, archives and web views

Universal links and URL schemes

Any app can claim a custom URL scheme, which makes schemes unsuitable for OAuth redirects or any link carrying a secret (ATT&CK for Mobile T1635.001 URI Hijacking). Universal links bind a domain to your app through the apple-app-site-association file, served at https://<domain>/.well-known/apple-app-site-association over HTTPS with a valid certificate and no redirects. Each subdomain needs its own entitlement entry and its own file. Use components with exclude rules so only the paths your app genuinely handles open in it. Since iOS 14 devices fetch the file through Apple's CDN, which requests it within 24 hours, and devices check for updates roughly weekly, so plan path changes ahead. For OAuth sign-in, ASWebAuthenticationSession with PKCE is the established pattern; see the OAuth 2.0 and OpenID Connect Guide.

In the handler (onOpenURL, application(_:open:options:) or the user activity continuation), parse with URLComponents, compare host and path against an allowlist, validate every query item's type and length, and confirm the user is signed in and authorised before any state change. A link should navigate, not act.

Archives and object graphs

Apple's NSSecureCoding documentation explains the problem with the old pattern: by the time a decoded object's class is checked, it has already been constructed and possibly inserted into an object graph. Conforming classes return true from supportsSecureCoding and decode nested values with decodeObject(of:forKey:). Decode root objects with NSKeyedUnarchiver.unarchivedObject(ofClass:from:) or the ofClasses variant listing every expected class. For JSON, decode into specific Codable structs and avoid decoding to [String: Any] and casting later. See the Secure Deserialisation Guide.

WKWebView

  • File access: loadFileURL(_:allowingReadAccessTo:) grants read access to the directory you name; pass the narrowest directory holding the bundled content, never the Documents or Application Support root.
  • JavaScript calls: do not build JavaScript by string interpolation for evaluateJavaScript. callAsyncJavaScript(_:arguments:in:contentWorld:) passes values as arguments, and a separate WKContentWorld keeps your scripts isolated from page scripts.
  • Message handlers: in WKScriptMessageHandler, check message.frameInfo.isMainFrame and the security origin before acting, and validate the body type.
  • Navigation: use WKNavigationDelegate to allowlist hosts; open everything else in Safari or SFSafariViewController.
  • Inspection: set isInspectable only in debug builds.

Memory, concurrency and data handling

  • Contain unsafe code: Swift is memory safe by default; UnsafeMutablePointer, UnsafeRawBufferPointer, unsafeBitCast and C interop are where buffer bugs return. Keep them in small, reviewed files and fuzz parsers that use them. See the Memory-Safe Languages Guide.
  • Turn on data race checking: the Swift 6 language mode reports data races at compile time; races around session state and token refresh cause authentication bugs that are hard to reproduce.
  • Protect files at write time: write sensitive files with Data.WritingOptions.completeFileProtection and exclude caches of personal data from backup where appropriate.
  • Logging: with os.Logger, dynamic strings are redacted as private in released logs by default; never mark tokens or PII as .public, and remove print() of model objects.
  • Pasteboard and snapshots: the general pasteboard is readable by other apps (ATT&CK for Mobile T1414 Clipboard Data); use a named local pasteboard or set expiry for copied codes, and cover sensitive screens before the app switcher snapshot.

Dependencies and the build

Commit Package.resolved for apps so every build resolves the same package versions, review diffs to it like code, and prefer exact versions for security-sensitive packages. Binary targets and XCFrameworks cannot be reviewed as source, so require a checksum and a vendor privacy manifest. Scan the repository and the archived IPA for secrets before submission, because Apple's review does not look for them. Keep debug-only endpoints, test accounts and authentication bypass flags behind #if DEBUG so they are not compiled into release. See the SBOM Guide and the Git Secret Scanning Guide.

Choosing controls by app risk

App profileBaselineAdd for higher assurance
Content or utility app, small teamNo embedded secrets, ATS without exceptions, typed Codable, Package.resolved committedUniversal links for any sign-in flow
Accounts and personal dataKeychain with ThisDeviceOnly classes, .completeFileProtection, NSSecureCoding, WKWebView allowlists.userPresence on refresh tokens, NSPinnedDomains with backup pins
Banking, health or paymentsAll of the above plus Secure Enclave signing keys and App Attest-gated token issuance.biometryCurrentSet for transaction keys, MASVS L2 testing, independent crypto review
Many apps across an organisationShared Swift package with keychain, crypto and web view wrappersCentral SwiftLint rules and metrics across repositories

Rolling out a Swift secure coding standard

  1. Inventory: list every keychain call, UserDefaults key, URL handler, WKWebView, unarchiver, custom trust handler and Info.plist ATS exception.
  2. Rotate and remove secrets: revoke embedded keys first, because old app versions keep them; then replace them with a backend exchange.
  3. Ship shared wrappers: one keychain wrapper with safe defaults, one CryptoKit helper, one web view factory, so the secure option is the easy one.
  4. Gate in warning mode: add SwiftLint custom rules (for example, banning Insecure outside an interop folder, evaluatePolicy followed by UserDefaults reads, and server trust overrides) and secret scanning as warnings for two to four weeks.
  5. Enforce and migrate data: make rules errors on the release branch; migrate existing items to stricter accessibility classes in an app update that reads the old item, writes the new one and deletes the old.
  6. Test in rings with rollback: use TestFlight groups and phased App Store release; if stricter pinning or keychain changes break sign-in, pause the phased release and ship a fix, since a pinned configuration cannot be reverted server-side.

Detection and measurement

  • Secrets in the IPA: keys found by scanning each archived build; target zero.
  • Keychain coverage: share of tokens and keys stored with a ThisDeviceOnly class and access control.
  • Trust overrides: count of custom server trust handlers and ATS exceptions per release, with review required for any increase.
  • Unsafe API debt: open lint findings for Insecure, unsafe pointers outside approved files and non-secure unarchiving.
  • Server-side rejections: failed App Attest assertions, invalid tokens and rejected universal link parameters, which reveal tampering and probing.

Framework mapping

FrameworkReferenceSwift and iOS coding practice
NIST SP 800-53 Rev. 5SA-15; SA-11Secure coding standard, lint gates, MASVS-based testing
NIST SP 800-53 Rev. 5SC-12; SC-13; SC-28; IA-5CryptoKit, Secure Enclave keys, keychain access control
NIST SP 800-53 Rev. 5SC-8; SI-10; SR-3No trust overrides; URL and archive validation; dependency pinning
NIST CSF 2.0PR.PS-06; PR.DS-01; PR.DS-02Secure development; data at rest and in transit
MITRE ATT&CK for MobileT1409 Stored Application Data; T1414 Clipboard Data; T1635.001 URI Hijacking; T1638 Adversary-in-the-MiddleStorage, pasteboard, link and transport controls above
OWASP MASVSMASVS-STORAGE, CRYPTO, AUTH, NETWORK, PLATFORM, CODE, PRIVACYVerification categories for each section

Common failure patterns

  • Payment and cloud keys in the bundle: Cybernews analysed 156,080 iOS apps and found at least one hard-coded secret in 71%, including Stripe secret keys; see the iOS Apps Leaking Hard-Coded Secrets 2025 analysis.
  • SDKs carrying credentials: in the Mobile Apps Hard-Coded AWS Keys 2022 research, about 98% of the 1,859 affected apps were iOS, and shared libraries spread the same AWS keys across developers.
  • Face ID as a Boolean: evaluatePolicy success unlocks a token stored without access control.
  • Trust-everything delegate: a challenge handler written for a staging proxy ships to production.
  • Custom scheme OAuth redirect: another app registers the same scheme and receives the authorisation code.
  • Backend trusts the app: a database open to anyone holding its URL, as in the Firebase Misconfigurations 2024 exposure.

Lessons from incidents

Both studies show that app binaries are mined for secrets at scale, that store review does not catch them, and that revocation breaks installed versions. Treat the app as a public client: it proves its integrity with App Attest, the backend issues short-lived scoped tokens, and the keychain protects them on device. Those tokens are non-human identities with an owner and a lifecycle; see the OWASP NHI Top 10 NHI1 Improper Offboarding Guide.

Practitioner checklist

  • Scan the source and archived IPA for secrets; revoke and replace anything found.
  • Move every token and key from UserDefaults or files into keychain items with a ThisDeviceOnly class and SecAccessControl.
  • Replace evaluatePolicy-only gates with keychain-protected items and add NSFaceIDUsageDescription.
  • Replace CommonCrypto and hand-built crypto with CryptoKit; ban Insecure outside interop code.
  • Delete custom server trust handlers that do not evaluate trust; pin with NSPinnedDomains and a backup pin.
  • Move sign-in and sensitive links to universal links with tight AASA components; validate every parameter.
  • Adopt NSSecureCoding and class-restricted unarchiving everywhere archives are decoded.
  • Harden WKWebView: narrow file read access, argument-based JavaScript calls, origin checks in message handlers, isInspectable off in release.
  • Commit Package.resolved and review dependency and binary target changes.
  • Track the five metrics above at every release gate.

Standards and references

Related NHI Mgmt Group resources: iOS App Security Guide · Kotlin and Android Secure Coding Guide · Mobile App Security Testing Guide · Secure Software Development Lifecycle (SSDLC) Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 8 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.