/Learn
Modules · Mobile systems · Deep dive

Mobile Security: Tokens, Keystore, Pinning and Tampering

LearnDeep diveTier 2 · MechanismsAnalyze15 minMobile systems

You will be able to: design token storage and refresh for a mobile app, and explain which defences hold on a compromised device.

Prove it: Offline-first inspection app with huge uploads

Source: OWASP MASVS and MASTG; RFC 8252 (OAuth for native apps)

Mobile engineeringReact Native in one place15 of 22Next: Mobile Observability: Crashes, ANRs, Traces and Rollout Gates →

Payments assumes the phone can't be trusted, and Priya's offline data sits on a phone that could be stolen. This module covers both. Start from the basics in Day 11 →

Study with AI

Part 1 of 5

Basics

The whole idea first, then the terms the rest of this page uses.

1.1Whole idea

The app and everything in it sits on a device the attacker may control. Treat the client as untrusted, keep real authority on the server, store secrets in hardware-backed storage, and make stolen credentials short-lived and revocable.

Why it matters

Assume the phone can be lost, rooted or reverse-engineered, then decide what an attacker still cannot do.

1.2Key concepts

One idea per card, in plain words.

01Access and refresh tokens

A short-lived token for calls and a longer-lived one to get new tokens. Rotate the refresh token on each use.

02Keystore and Keychain

Hardware-backed storage for keys on Android and iOS. The key stays in secure hardware even if files leak.

03PKCE

Protects the native sign-in flow, so an intercepted code is useless alone.

04Certificate pinning

Accepts only known server keys. Strong against interception, and risky if a key rotates unexpectedly.

05App attestation

Play Integrity and App Attest let the server check that a request came from a genuine app.

Part 2 of 5

Question

What exactly you must answer, and what to settle before you start.

2.1Question

Interviewer

Field technicians store customer data offline on shared phones, and security reports that a stolen phone exposed a session. Redesign token handling and data protection.

2.2Clarify first

Each answer removes a guess.

You askAnswer
What must work offline?Reading and editing assigned jobs. Sign-in needs a network; unlocking the app does not.
Who can revoke access?An administrator, within minutes, when a phone is reported lost.
Part 3 of 5

Detailed answer

How it works, and how to build or explain it.

3.1Step by step

The mechanism, in the order you would explain it.

  1. Sign in with PKCE

    Use the system browser and PKCE. Never collect passwords in a WebView.

  2. Store keys in hardware

    Generate a database key in the Keystore or Keychain, and encrypt SQLite with it, as the offline app does with SQLCipher.

  3. Refresh once at a time

    Use one single-flight refresh: many 401s must trigger one refresh, and the rest wait for its result.

  4. Rotate and detect reuse

    Each refresh issues a new refresh token. Reuse of an old one signals theft, so revoke the whole session.

  5. Separate unlock from sign-in

    Biometric unlock opens the local key offline. Server access still depends on valid tokens.

  6. Wipe on revocation

    The next sync that learns of revocation deletes local data and the key. Files without their key are unreadable.

3.2Code

A working implementation, then what each part does and why.

Refreshing a token only once

When a token expires, ten requests can fail together. If each one refreshes, rotation treats the repeats as theft and logs the user out.

TokenRefresher.ktKotlin
1data class Tokens(val access: String, val refresh: String)2 3/** Ten requests can get a 401 at once. Only the first refreshes, and the rest wait for its result. */4class TokenRefresher(5  private var tokens: Tokens,6  private val callRefresh: suspend (refreshToken: String) -> Tokens,7) {8  private val lock = Mutex()9  private var inFlight: CompletableDeferred<Tokens>? = null10 11  val current: Tokens get() = tokens12 13  /** [stale] is the access token that just failed. */14  suspend fun refreshed(stale: String): Tokens {15    val mine = CompletableDeferred<Tokens>()16    val joined = lock.withLock {17      if (tokens.access != stale) return tokens       // someone already replaced it18      inFlight?.also { return@withLock it }19      inFlight = mine20      null21    }22    if (joined != null) return joined.await()23    try {24      val fresh = callRefresh(tokens.refresh)         // rotates the refresh token too25      lock.withLock {26        tokens = fresh27        inFlight = null28      }29      mine.complete(fresh)30      return fresh31    } catch (e: Exception) {32      lock.withLock { inFlight = null }33      mine.completeExceptionally(e)34      throw e35    }36  }37}
37 linesUTF-8Kotlin
if (tokens.access != stale) return tokens
Someone already replaced this token, so use the new one.
inFlight?.also { return@withLock it }
A refresh is running, so join it rather than starting another.
callRefresh(tokens.refresh)
Runs outside the lock, so waiting requests never block on the network while holding it.
completeExceptionally(e)
If the refresh fails, everyone waiting finds out, and the old tokens stay.

Compiled and tested by npm run test:mobile.

Part 4 of 5

Q&A

What interviewers ask next. Answer out loud, then open.

4.1Interview questions

Should you pin certificates?
Only with a backup pin and a remote way to update pins. A mistake locks every user out until they update.
Does root detection stop attackers?
It raises the cost and nothing more. Enforce permissions on the server.
Where do API keys belong?
Not in the app: anything shipped can be extracted. Proxy third-party calls through your backend.
Part 5 of 5

Extra depth

Edge cases, counterpoints and what to read next.

5.1Edge cases and counterpoints

Includes the strongest argument against this approach.

Show detailsHide details
Screenshots and logs
Hide sensitive screens from the app switcher, and keep tokens out of logs and crash reports.
Backups
Exclude token and database files from device backups.
Counterpoint
Every control adds friction. For low-risk data, heavy attestation and pinning may cost more than they protect.
AI Engineer · Mobile Security: Tokens, Keystore, Pinning and Tampering