Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 80 ยท Secure Coding

Mobile Application Security

Learn how to build and assess secure mobile apps: threat model, secure data storage, permissions, network security and pinning, authentication, code protection and testing methods.

A mobile app runs on a device you do not control, belongs to a user you cannot see, and travels through networks you do not trust. The phone may be lost, rooted, infected, or running an outdated operating system. The app's code ships to every user, so anyone can download it and study it. Yet the same phone holds banking, health, messaging and work data, so apps are an attractive target.

Mobile security therefore starts from a different assumption than web security: the client is untrusted. Anything stored on the device or compiled into the app can be inspected, and anything the app sends can be intercepted unless it is protected. This lesson covers the mobile threat model, secure storage, permissions, network security, authentication, code protection and the main kinds of testing. The code samples are small Python models of the ideas; the guidance applies to Android, iOS and cross-platform frameworks alike. It builds on Secure Coding Principles, API Security and TLS, Certificates and PKI.

The mobile threat model

Think in terms of where an attacker can be:

  • On the network: public Wi-Fi, malicious hotspots and compromised routers can read or change traffic if it is not protected (VPNs, Wi-Fi and Remote Access Security).
  • On the device: another malicious app, malware, a stolen or lost phone, or a user-modified (rooted or jailbroken) system.
  • In the app itself: a downloaded and decompiled copy, tampered and re-distributed (repackaging), or running under a debugger or instrumentation tool (Reverse Engineering Basics).
  • At the back end: the APIs the app talks to. These are the most valuable target, because they hold the real data (API Security).
  • In the supply chain: third-party libraries and SDKs bundled into the app (Dependency and Supply Chain Security).

Industry guidance such as the OWASP Mobile Top 10 and the OWASP MASVS (Mobile Application Security Verification Standard) lists the recurring problems: improper credential usage, insecure authentication and authorization, insufficient input and output validation, insecure communication, inadequate privacy controls, insufficient binary protection, security misconfiguration, insecure data storage and weak cryptography. The sections below address them in turn.

Secure data storage

The rule is: store as little as possible on the device, and protect what you must store.

  • Do not hard-code secrets (API keys, passwords, signing keys) in the app: anyone can extract them from the package. Put secrets on a server and give the app short-lived tokens (Secrets, Logging and Error Handling).
  • Use the platform's secure storage for tokens and keys: the Android Keystore and iOS Keychain, which can keep keys in secure hardware so that they cannot be copied out, and can require the user's biometric or screen lock to use them.
  • Encrypt sensitive local data (databases, files) with a key from that secure storage, and use authenticated encryption (Symmetric Encryption and Modes).
  • Avoid leaking data to places other apps or people can read: shared or external storage, clipboard, logs, crash reports, screenshots in the app switcher, keyboard caches and backups.
  • Choose the minimal retention: clear caches, tokens and sensitive screens on logout; do not keep full card numbers or national IDs.
  • Do not trust local checks such as a stored "isPremium" flag or "isAdmin" setting; the server must decide.

The model below shows the difference between a token saved in plain text and one protected with a key that lives elsewhere (here a stand-in "keystore" object). The cipher is a toy built from SHA-256 and HMAC to keep the example self-contained; use the platform's real crypto APIs.

Python Plain storage vs key-protected storage

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hardware-backed key storage means that even if an attacker copies the encrypted file, the key stays in the secure element or trusted environment and can be bound to the device and the user's authentication.

Permissions and privacy

Mobile operating systems protect sensitive capabilities (camera, microphone, contacts, location, storage, notifications) behind permissions that the user grants.

  • Request only what you need, and only at the moment of use, explaining why. Over-requesting reduces trust and increases the damage if the app is compromised.
  • Prefer narrower options: approximate location instead of precise, a photo picker instead of full storage access, "only while using the app".
  • Protect exported components. On Android, activities, services, receivers and content providers that are exported can be called by other apps; export only what is necessary, require permissions, and validate every input, including intents and deep links. On iOS, validate URL schemes and universal links.
  • Handle deep links as untrusted input, and never place sensitive actions behind a link that works without re-authentication.
  • Respect privacy law and store policies: disclose data collection, minimize identifiers, and give users deletion options (Privacy and Data Protection).
  • Be careful with third-party SDKs: analytics and advertising libraries inherit your permissions and may collect more than you expect.

A simple audit can compare an app's requested permissions with what its features need:

Python Permission audit against declared features

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Secure communication

Assume the network is hostile.

  • Use TLS for all traffic, with modern versions and no cleartext fallback. On Android, disable cleartext traffic in the network security configuration; on iOS, leave App Transport Security enabled.
  • Validate certificates properly. Never disable hostname or certificate checks to "make the test server work", and never ship code that accepts every certificate; that turns TLS into theatre and enables man-in-the-middle attacks (Common Network Attacks and Defenses).
  • Consider certificate or public-key pinning for high-risk apps: the app accepts only a specific key (or one of a small set, including a backup) for your server, so a rogue or compromised certificate authority cannot be used against it. Pinning needs a rotation plan, because a wrong pin locks users out of the app until it is updated.
  • Do not put secrets in URLs or logs; use headers and request bodies.
  • Treat the API as the real security boundary: authenticate and authorize every request on the server, and do not rely on the app to enforce rules (API Security).

The model below shows how pinning works: the app compares the hash of the server's public key with a stored pin set, so a certificate that is "valid" but from a different key is rejected.

Python How public-key pinning decides

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pinning does not stop an attacker who controls the device (they can bypass it with instrumentation), so treat it as one layer against network attackers, not a way to hide secrets.

Authentication and sessions

  • Use standard flows: OAuth 2.0 with PKCE through the system browser (not an embedded web view that can capture credentials), and the platform's passkey or biometric APIs (OAuth 2.0, OpenID Connect and SSO, Multi-Factor Authentication and Passkeys).
  • Prefer short-lived access tokens with revocable refresh tokens kept in secure storage; support server-side logout and revoke tokens when a device is lost.
  • Biometrics unlock a key or token on the device; the server still verifies a cryptographic proof or token, never "the fingerprint matched" as a boolean from the client.
  • Re-authenticate before sensitive actions (payments, changing credentials).
  • Rate limit and monitor login and token endpoints on the server, because mobile clients can be automated (Sessions, Cookies and JWTs).

Code and runtime protection

Because the app can be analyzed, add friction for attackers without pretending it is impossible:

  • Obfuscation and shrinking (for example R8 on Android, symbol stripping on iOS) make reverse engineering harder but not impossible.
  • Integrity and environment checks: detect tampering, debuggers, emulators and rooted or jailbroken devices, and respond by limiting sensitive features or flagging the session server-side. Treat these as risk signals; skilled attackers bypass client checks.
  • Platform attestation: attestation services let your server ask whether a request comes from a genuine app on a genuine device.
  • Sign and distribute through official stores, protect signing keys, and keep your CI pipeline secure.
  • Keep dependencies updated, monitor for vulnerable libraries, and remove unused SDKs.
  • Do not log sensitive data, and disable debug features and verbose logs in release builds.
  • Never rely on client-side secrecy: put licensing, pricing and authorization logic on the server.

Testing mobile apps

A mature program uses several test types together (Security Code Review, SAST and Testing):

Type What it does Finds
SAST (static application security testing) Scans source code or compiled code without running it Hard-coded secrets, insecure API use, risky patterns
DAST (dynamic testing) Exercises the running app and its network behaviour Missing TLS validation, insecure responses, injection
IAST (interactive testing) Instruments the app during tests Precise data-flow issues at run time
SCA (software composition analysis) Checks libraries against vulnerability databases Known vulnerable dependencies
Manual penetration testing and reverse engineering Skilled testers examine the app, device storage and API Logic flaws, bypasses, insecure storage
API testing Tests every back-end endpoint for authorization and abuse Broken object-level authorization, excessive data exposure

Use the MASVS as the checklist for what to verify, and its companion testing guide for how; use authorized test devices and test accounts only. Run these checks in the build pipeline and before every release, and plan a process for receiving and fixing vulnerability reports, including a way for researchers to contact you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a mobile app keep a long-lived refresh token?

    Secure storage can protect keys and secrets in hardware and tie their use to the device and the user's authentication.
  2. 2. Why is a hard-coded API key inside a mobile app a problem?

    The app package is available to every user and can be decompiled, so secrets inside it are not secret. Keep them on a server.
  3. 3. What is the main risk of disabling TLS certificate validation to make testing easier and shipping it?

    Without validation the app accepts any certificate, including an attacker's. Fix the test environment instead of weakening the client.
  4. 4. Which statement about root and jailbreak detection is most accurate?

    Client-side checks raise the cost of attack. Real enforcement must stay on the server.

Summary

  • Treat the mobile client as untrusted: the device, network and even the app copy can be attacked.
  • Store little, use Keystore or Keychain for secrets, encrypt local data, never hard-code keys, and avoid leaking through logs, backups and clipboards.
  • Request minimal permissions, protect exported components and deep links, and audit third-party SDKs.
  • Use TLS everywhere with proper validation; consider pinning with a rotation plan.
  • Use OAuth with PKCE, short-lived tokens and server-side checks; biometrics unlock local keys, not server trust.
  • Add obfuscation and integrity signals as friction, but keep decisions on the server.
  • Test with SAST, DAST, SCA, manual penetration testing and API testing against the MASVS.

Next: Security Code Review, SAST and Testing to see the general testing practices in more depth.