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.

Open Interactive Chapter →

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.
SeniorUses EncryptedSharedPreferences for token storage
StaffDesigns full auth flow: JWT rotation, OkHttp Authenticator for 401 replay, biometric gate for sensitive screens
PrincipalOwns the auth architecture across the app — token lifecycle, revocation, PII minimisation, threat model

Encrypted Storage

Different storage solutions for different types of sensitive data.

Data TypeStorage Solution
Auth tokens, session keysEncryptedSharedPreferences (API 23+)
Cryptographic private keysAndroid Keystore System — keys never leave secure hardware
Sensitive structured dataRoom + SQLCipher (encrypted SQLite)
Small sensitive preferencesDataStore 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.
RegulationJurisdictionKey Engineering Requirements
GDPREU / EEA usersExplicit 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 / CPRACalifornia usersDisclose categories of data collected; honor opt-out of sale/sharing; right to deletion; 45-day response window
COPPAUnder-13 users (US)Parental consent before any data collection; no behavioral advertising; strict data retention limits
HIPAAUS health dataPHI (Protected Health Information) must be encrypted at rest and in transit; strict access logging; no PHI in crash logs or analytics
SeniorKnows not to log PII; uses EncryptedSharedPreferences for sensitive data
StaffDesigns the consent gate, the deletion flow, and the data minimization policy; knows which regulations apply to the app's user base
PrincipalOwns the privacy architecture across the platform — consent lifecycle, data classification, retention policy, breach response plan

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
SeniorShows a consent dialog before initializing analytics SDKs
StaffImplements granular consent, persists consent state correctly, and designs the deletion flow
PrincipalDefines the privacy engineering standard across the platform including data classification, retention schedules, breach response, and audit logging

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.

Test your knowledge

This chapter includes 7 quiz questions covering all core concepts. Open the interactive experience to test yourself.

Start Quiz →