Chapter 8
Security & Privacy
Auth · Token Storage · Certificate Pinning · WebView · Multi-Process · Encryption
Ready to practise interactively?
Explore this chapter with quizzes, diagrams, and real-world examples in the full interactive experience.
Authentication & Token Management
Critical security concepts for mobile apps.
- JWT + refresh token rotation — short-lived access tokens (15min); long-lived refresh token (30 days)
- OkHttp Authenticator — intercepts 401 automatically, refreshes token, replays original request transparently
- Token storage — EncryptedSharedPreferences for tokens; Android Keystore for cryptographic key material
- Never — store tokens in plain SharedPreferences, SQLite without encryption, or logs
- Biometric auth — use BiometricPrompt API; authenticate before showing sensitive data
Recommended Libraries
- EncryptedSharedPreferences — Jetpack Security library for encrypted key-value storage. Use for tokens and sensitive preferences.
- Biometric — Jetpack library for fingerprint/face authentication. Use BiometricPrompt API for sensitive actions.
- AppAuth — OAuth 2.0 / OpenID Connect client for Android. Handles auth flows, token refresh, PKCE.
Encrypted Storage
Different storage solutions for different types of sensitive data.
| Data Type | Storage Solution |
|---|---|
| Auth tokens, session keys | EncryptedSharedPreferences (API 23+) |
| Cryptographic private keys | Android Keystore System — keys never leave secure hardware |
| Sensitive structured data | Room + SQLCipher (encrypted SQLite) |
| Small sensitive preferences | DataStore with EncryptedFile |
| Files (documents, downloads) | EncryptedFile from Jetpack Security |
Certificate Pinning
Prevent MITM attacks by ensuring the server's certificate matches a known pinned value.
- Purpose — prevent MITM attacks by ensuring the server's certificate matches a known pinned value
- OkHttp CertificatePinner — easiest implementation; pin by hostname and certificate hash
- Backup pins — always include at least one backup pin for the CA or intermediate cert
- Pin rotation plan — plan before deployment; coordinate with server team; if pin expires without rotation, app stops working
- Network Security Config — declarative pinning via XML; good for debug/release separation
WebView Security
WebView is a significant attack surface. Palo Alto Networks will ask about this.
- JavascriptInterface — exposed methods are callable from any JS in the WebView; only expose what is absolutely necessary; validate all inputs
- shouldOverrideUrlLoading — intercept navigation; reject unexpected protocols or domains
- SSL error handling — never call handler.proceed() in onReceivedSslError(); reject and show error
- Chrome Custom Tabs — prefer over WebView for opening external URLs; runs in browser process (sandboxed), supports saved passwords and autofill
- File access — disable setAllowFileAccess() and setAllowUniversalAccessFromFileURLs() unless required
Multi-Process Architecture
Android apps can run components in separate processes. Relevant for crash isolation and memory.
- Why use it — isolate unstable components (WebView, media codec) so their crash doesn't kill the main process
- Declare in manifest — android:process=':isolated' on a component
- IPC mechanisms — AIDL (typed), Messenger (message-based), BroadcastReceiver (fire-and-forget), ContentProvider (data sharing)
- Binder — Android's IPC mechanism; transactions are synchronous; avoid on main thread
- Memory — each process has its own heap; total memory use increases; Application.onCreate() is called once per process
ProGuard / R8 & Code Hardening
Code obfuscation and security hardening.
- R8 — default shrinker/obfuscator in Android build; renames classes and methods to single chars
- Keep rules — add -keep rules for reflection-used classes, serialization, and JNI entry points
- Repackaging — move all classes to a single package to further obscure structure
- Root/tamper detection — check for root indicators (su binary, test-keys), debugger attachment, and app signature for high-security apps (banking, Palo Alto)
Privacy Engineering — GDPR, CCPA & On-Device PII
Privacy compliance is no longer a legal checkbox — it is a Staff-level engineering topic. Regulations dictate architecture decisions: what you collect, where you store it, how long you keep it, and how you delete it. Interviewers at companies with regulatory exposure (fintech, health, social) now probe this directly.
- Data minimization — collect only what you need for the stated purpose. Every field in your analytics schema should have a documented business justification.
- PII in logs — never log email, phone, device ID, or any personally identifiable value. Use hashed or anonymized identifiers in logs and crash reports.
- Right to erasure — design the deletion path before launch, not after a regulator asks. Cascading deletes across Room, the backend, analytics, and backups must all be coordinated.
- Data residency — EU users' data may not leave the EU without contractual safeguards. Architecture must support regional data routing from day one if EU expansion is planned.
- On-device processing preference — process sensitive data on-device where possible (ML inference, health calculations) to avoid transmitting raw PII to servers at all.
- Consent SDK — implement a consent management platform (OneTrust, Usercentrics) before enabling any third-party analytics or ad SDK. SDKs must not fire before consent is granted.
| Regulation | Jurisdiction | Key Engineering Requirements |
|---|---|---|
| GDPR | EU / EEA users | Explicit consent before collection; right to erasure (delete within 30 days); data portability; breach notification within 72 hours; no data transfer outside EEA without adequacy decision |
| CCPA / CPRA | California users | Disclose categories of data collected; honor opt-out of sale/sharing; right to deletion; 45-day response window |
| COPPA | Under-13 users (US) | Parental consent before any data collection; no behavioral advertising; strict data retention limits |
| HIPAA | US health data | PHI (Protected Health Information) must be encrypted at rest and in transit; strict access logging; no PHI in crash logs or analytics |
Consent Architecture on Android
Consent is a technical engineering problem, not just a UI problem. The consent state must gate SDK initialization, analytics calls, and data collection — and it must persist correctly across process death, app updates, and consent withdrawal.
- Consent state storage — persist to EncryptedSharedPreferences or DataStore; never in-memory only; must survive process death
- Granular consent — GDPR requires separate consent per purpose (analytics, personalization, advertising); a single 'accept all' is increasingly challenged by regulators
- Consent SDK initialization gate — wrap all third-party SDKs in a consent-checked initializer; uninitialize on withdrawal if the SDK supports it
- Consent withdrawal — user must be able to withdraw at any time; match the ease of withdrawal to the ease of granting (if one tap to accept, one tap to withdraw)
- Consent version migration — when your privacy policy changes, existing consent may become invalid; implement a consent version check on app launch
- Age gating — if your app may be used by under-13s, implement age verification before any data collection begins; COPPA applies regardless of geography if the user is in the US
Interview tip: If asked about privacy in a system design: lead with 'I'd start by identifying which regulations apply to our user base, then define our data classification tiers — what we collect, why, and for how long. The consent gate and deletion flow are engineering requirements, not afterthoughts.' That answer signals Staff-level ownership of the problem.