Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 71 ยท Quality

Mobile App Security

Protect a React Native app: keep secrets out of the bundle, store tokens safely, understand certificate pinning, root detection, obfuscation and OWASP MASVS.

On the web, your code runs on your server and the browser only gets the result. A mobile app is the opposite: you hand a copy of your program to every user, including the ones who want to take it apart. Anyone can download your app, unzip it, read the JavaScript bundle, watch its network traffic and run it on a phone they control. Mobile security starts from that one fact: the app is not a safe place to hide anything.

This lesson explains what that means in practice: which things must never be in the bundle, where to keep tokens, what certificate pinning and root detection really buy you, and how the OWASP MASVS checklist helps you decide what to do. General web-side ideas are in React Security; here we cover what is specific to phones.

Read-only and stand-in. Keychain, Keystore and TLS pinning live in the operating system, so the real code is shown in plain blocks. The TryIts are stand-ins that you can run anywhere: a token expiry checker and a bundle secret scanner.

Rule one: no secrets in the bundle

Your JavaScript bundle ships inside the app. Hermes compiles it to bytecode, but bytecode is not encryption: tools exist that turn it back into readable strings and logic in minutes. So anything you put in the bundle is public:

  • Environment variables that Expo exposes to the app (anything starting with EXPO_PUBLIC_ is inlined into the bundle on purpose).
  • API keys written in constants, config files or app.json extra values.
  • "Hidden" admin URLs, feature flags that unlock paid features, and hard-coded passwords.

Ask of every value: if a stranger read this, could they cause damage? Some values are public by design and safe to ship: a Sentry DSN, a Stripe publishable key, a Google Maps key that is restricted to your app's bundle identifier. Others are never safe: a Stripe secret key, a database connection string, a signing key, an OpenAI or cloud-provider key with full access, an auth token for your build service.

The fix is architectural, not technical. Put secrets on your server and let the app talk to your server:

sequenceDiagram
    participant App as Mobile app
    participant API as Your server
    participant Vendor as Third-party API
    App->>API: Request with the user's token
    Note over API: Secret key lives here
    API->>Vendor: Request with the secret key
    Vendor-->>API: Result
    API-->>App: Only the data the user may see

The app proves who the user is; the server holds the secret and decides what is allowed.

Your server must also check every request itself. Hiding a button in the app does not stop someone from calling the endpoint directly, so authorization always belongs on the server.

Storing tokens safely

After login, the server usually gives the app an access token (short lived) and often a refresh token (long lived). Where you keep them matters:

  • AsyncStorage stores plain text in the app's data folder. It is fine for preferences and caches, and a poor place for tokens: on a rooted or backed-up device the file can be read.
  • Secure storage uses the operating system's vault: the Keychain on iOS and the Keystore on Android (encrypted with a key the hardware protects). In Expo you use expo-secure-store; in a bare app a library such as react-native-keychain.
TSX
import * as SecureStore from 'expo-secure-store';

export async function saveRefreshToken(token: string) {
  await SecureStore.setItemAsync('refreshToken', token);
}

export async function readRefreshToken() {
  return SecureStore.getItemAsync('refreshToken');
}

export async function clearTokens() {
  await SecureStore.deleteItemAsync('refreshToken');
}

Secure storage is meant for small values (tokens, keys), not for databases or lists. The trade-offs, size limits and migration patterns are in Storing Data: AsyncStorage, MMKV and SecureStore.

Good token habits:

  • Keep access tokens short lived (minutes) so a stolen one stops working quickly.
  • Keep the access token in memory and only the refresh token in secure storage.
  • On logout, delete the tokens and tell the server to revoke the refresh token.
  • Never put tokens in URLs, logs or analytics events.
  • For "sign in with Google/Apple/GitHub", use the system browser session with the authorization code flow with PKCE. Never embed the provider's client secret in the app; a mobile app is a "public client" and cannot keep one.

Network security

All traffic must use HTTPS. Both platforms block plain HTTP by default in release builds, and you should not weaken that rule outside local development (see Networking with fetch).

Certificate pinning goes one step further. Normally the phone trusts any certificate signed by any of the many certificate authorities it knows. With pinning your app also checks that the server's certificate (or its public key) matches a fingerprint stored in the app, and refuses to talk otherwise. This blocks an attacker who has installed their own trusted certificate on the phone, for example to run a man-in-the-middle proxy.

Pinning has real costs:

  • If you pin one certificate and it expires or you change provider, every installed copy of the app stops working until users update. Pin the public key rather than the whole certificate, and always include a backup pin.
  • It makes your own debugging harder, because you cannot inspect your traffic with a proxy.
  • Plain React Native has no switch for it. You need a library or a native configuration, and in Expo a config plugin or a development build (see Native Modules, Expo Modules and Config Plugins).

Most apps do not need pinning. Banking, health and similar apps with strong threat models usually do. Decide on purpose and write the decision down.

Rooted and jailbroken devices

On a jailbroken iPhone or a rooted Android phone, the user (or malware) can bypass the operating system's protections: read other apps' files, hook functions at runtime and fake responses. Libraries can detect common signs of this.

Be honest about what detection gives you. Every check runs on the device, so an attacker who controls the device can patch the check out. Treat it as a speed bump and a risk signal, not as a lock. Reasonable uses: show a warning, disable the most sensitive features (payments, showing full account numbers), or send a signal to the server so it can apply stricter rules. Do not crash the app and call that security.

Obfuscation and reverse engineering

Hermes bytecode is harder to read than minified JavaScript, but it is not secret. Extra obfuscation tools exist, and on Android you can shrink and obfuscate the native Java/Kotlin side with R8 (the successor of ProGuard). They raise the effort needed to understand your app, nothing more. The consequence is the same as rule one: assume the logic is readable and keep decisions that matter (prices, permissions, licence checks) on the server.

Other things that leak

  • Logs. console.log output can be read from a connected phone. Remove logs that contain tokens, emails or personal data before release.
  • Screenshots and the app switcher. The task switcher shows a snapshot of your last screen. Sensitive apps hide the content when the app moves to the background (use AppState, see Platform APIs).
  • Clipboard. Other apps can read it. Do not copy secrets there silently.
  • Deep links. Any app or web page can open myapp://... with any parameters. Treat link parameters as untrusted input and validate them like form data (see Deep Linking and Authentication Flows).
  • Backups. Decide whether sensitive files should be included in device backups.

OWASP MASVS: a checklist to think with

The OWASP Mobile Application Security Verification Standard (MASVS) is a free list of security requirements for mobile apps, grouped into areas. It pairs with the MASTG, a testing guide with concrete procedures. You do not have to memorize it; the group names are a good prompt for a review:

MASVS areas, part one

Storage Is sensitive data kept safely?
Crypto Standard algorithms, no home-made ones.
Auth Login, sessions and tokens done right.
Network HTTPS everywhere, pinning if needed.
1 / 2

A to-do app and a banking app do not need the same level. Use the list to decide which areas matter for your data, then do those well. Two cheap habits help every app: run npm audit (or your package manager's equivalent) and keep dependencies updated, because a vulnerable library is part of your app too.

Stand-in: a token expiry checker

A signed-in app often decodes the access token to see when it expires, so it can refresh early instead of failing a request. The token below is a JWT built in the code. Decoding is not verifying: the app can read the claims but must never trust them for security. Only the server can check the signature.

Decode a token and decide when to refresh

Notice the SKEW margin. Phone clocks drift and requests take time, so refreshing slightly early is safer than waiting for the exact second.

Stand-in: a bundle secret scanner

Teams run scanners over the built bundle (and the repository) to catch accidental secrets before release. This stand-in uses four simple patterns on a fake bundle. All values are made up. Real scanners use many more patterns and also measure how random a string looks.

JS Scan a fake bundle for secrets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output lists the AWS key, the Stripe secret key and the password, and reports the publishable key and the Sentry DSN as public by design. Moving the first three to the server is the only real fix; deleting a secret from the code does not help once it shipped, so rotate (replace) every key that ever reached a build.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which value is safe to put in a React Native bundle?

    DSNs and publishable keys are designed to be public. Secret keys and connection strings give access to your systems and must stay on the server.
  2. 2. Where should a long-lived refresh token be stored?

    Secure storage uses the operating system's vault. AsyncStorage is plain text, and URLs or logs leak easily.
  3. 3. What is the main risk of pinning a single server certificate?

    A pin that no longer matches blocks all requests. Pin the public key, include a backup pin and plan for rotation.
  4. 4. What does jailbreak or root detection realistically give you?

    The check runs on the device, so a determined attacker can remove it. Use it to warn or restrict features, and keep real decisions on the server.
  5. 5. A decoded token says exp is in the future. Can the app trust this for security decisions?

    Decoding just reads the Base64 text. Use the expiry to decide when to refresh, and let the server validate every request.

Summary

  • Anything in the bundle is public: Hermes bytecode is not encryption. Keep secrets on your server and let the app call it.
  • Store tokens in secure storage (Keychain or Keystore); keep access tokens short lived and delete them on logout.
  • Use HTTPS everywhere; consider certificate pinning only with backup pins and a rotation plan.
  • Jailbreak/root detection and obfuscation are speed bumps; decisions that matter belong on the server.
  • Watch for leaks through logs, screenshots, the clipboard, deep links and backups.
  • OWASP MASVS gives you areas (storage, crypto, auth, network, platform, code, resilience, privacy) to review against your own risk.

Next, learn to dodge the mistakes almost every team makes in Common Pitfalls and Fixes.