Authentication & Security
The mobile security mindset
Treat the phone as an untrusted environment: it can be lost, stolen, rooted/jailbroken, or running on a hostile network. Your job is to authenticate users smoothly while protecting their tokens, data and communication. Security is a first-class part of mobile system design, not an afterthought.
Token-based authentication
Modern apps don’t send the password on every request. The user logs in once, and the server returns tokens:
- Access token — short-lived (minutes); sent with each API call to prove identity.
- Refresh token — long-lived; used to get a new access token when it expires, without re-login.
Store tokens securely — never in plain storage
This is critical: never keep tokens or passwords in plain SharedPreferences/UserDefaults — they can be read on a compromised device. Use the platform’s encrypted secure storage:
- Android — the Keystore (e.g. EncryptedSharedPreferences / DataStore with Keystore).
- iOS — the Keychain.
Silent token refresh
When the access token expires mid-use, the app should refresh it transparently — no logout. A networking interceptor catches a 401, uses the refresh token to get a new access token, and retries the original request. Handle the case where the refresh token itself is invalid (then truly log out).
Biometric authentication
For convenience and security, gate sensitive actions or app entry behind biometrics (fingerprint/Face ID) using BiometricPrompt (Android) or LocalAuthentication (iOS). The biometric unlocks a key in secure storage — the app never sees the actual fingerprint.
Protecting data in transit and at rest
- In transit — always HTTPS/TLS. For high-security apps, add certificate pinning to prevent man-in-the-middle attacks on hostile networks.
- At rest — encrypt sensitive local data; rely on the OS’s file encryption and secure storage.
- Minimise — don’t store sensitive data you don’t need.
More good practices
- Never hard-code secrets/API keys in the app — they can be extracted; proxy through your backend.
- Use OAuth/OpenID Connect for “Sign in with Google/Apple” rather than rolling your own.
- Handle logout fully — clear tokens and sensitive caches.
- Obey least privilege — request only the permissions and scopes you need.
Common mistakes
- Storing tokens/passwords in plain preferences.
- No silent refresh, forcing users to log in repeatedly.
- Hard-coding API keys/secrets in the app.
- Skipping HTTPS or trusting any certificate.
Summary: Authenticate with short-lived access + long-lived refresh tokens, stored in the Keystore/Keychain (never plain storage). Refresh silently via an interceptor, gate sensitive actions with biometrics, always use HTTPS (consider cert pinning), keep secrets off the device, and treat the phone as untrusted.